os.path.join 用法

寫在前面:看你們閱讀量這麼大,也應該在放點乾貨來了~~

獲取層級路徑,直到能夠獲取文件夾下面的文件,多一個判斷就好了:

level1_list = [os.path.join(base_path, f) for f in listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]spa

結合路徑:code

原來的目錄層級:c:/a/b/c/test.pyblog

print os.path.abspath("%s" % __file__)ip

==> c:/a/b/c/test.pyit

print os.path.abspath("%s/../../" % __file__) #絕對路徑,相比下個路徑實現方式須要多跳出一次,坑。。。,不建議用class

==> c:/a/btest

print '-----'

file_path = os.path.split(os.path.realpath(__file__))[0] #建議使用
print file_path
==> c:/a/b/c/

print os.path.abspath("%s/../" % __file__)
import

此處跳到:c:/a/b/c file




kaggle-word2vec-ipynb >>> import os >>> datafile = os.path.join('/kaggle-word2vec-ipynb','/data/', 'labeledTrainData.tsv') >>> print datafile /data/labeledTrainData.tsv >>> datafile = os.path.join('kaggle-word2vec-ipynb','/data/', 'labeledTrainData.tsv') >>> print datafile /data/labeledTrainData.tsv #想要的路徑 >>> datafile = os.path.join('./kaggle-word2vec-ipynb/','data/', 'labeledTrainData.tsv') >>> print datafile ./kaggle-word2vec-ipynb/data/labeledTrainData.tsv #"/"出如今第一個,因此能夠追蹤合併到第一個 >>> datafile = os.path.join('/kaggle-word2vec-ipynb/','data/', 'labeledTrainData.tsv') >>> print datafile /kaggle-word2vec-ipynb/data/labeledTrainData.tsv
#"/"出如今第二個,因此從第二個開始,如下類推
>>> datafile = os.path.join('/kaggle-word2vec-ipynb','/data', 'labeledTrainData.tsv') >>> print datafile /data/labeledTrainData.tsv >>> datafile = os.path.join('/kaggle-word2vec-ipynb','/data', '/labeledTrainData.tsv') >>> print datafile /labeledTrainData.tsv >>> datafile = os.path.join('/kaggle-word2vec-ipynb','./data', '/labeledTrainData.tsv') >>> print datafile /labeledTrainData.tsv >>> datafile = os.path.join('/kaggle-word2vec-ipynb','data/', '/labeledTrainData.tsv') >>> print datafile /labeledTrainData.tsv >>> datafile = os.path.join('kaggle-word2vec-ipynb','data', 'labeledTrainData.tsv') >>> print datafile kaggle-word2vec-ipynb/data/labeledTrainData.tsv #想要的路徑 自動添加'/' >>> datafile = os.path.join('.','kaggle-word2vec-ipynb','data', 'labeledTrainData.tsv') >>> print datafile ./kaggle-word2vec-ipynb/data/labeledTrainData.tsv

總結:因此要麼不加 './' 或者"/",要麼中間的路徑不能出現'/'開頭,合併路徑感受是檢查了根目錄'/'的位置.im

仍是讓自動加上'/'就行

相關文章
相關標籤/搜索