寫在前面:看大家閱讀量這么大,也應該在放點干貨來了~~
獲取層級路徑,直到可以獲取文件夾下面的文件,多一個判斷就行了:
level1_list = [os.path.join(base_path, f) for f in listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]
結合路徑:
原來的目錄層級:c:/a/b/c/test.py
print os.path.abspath("%s" % __file__)
==> c:/a/b/c/test.py
print os.path.abspath("%s/../../" % __file__) #絕對路徑,相比下個路徑實現方式需要多跳出一次,坑。。。,不建議用
==> c:/a/b
print '-----'
file_path = os.path.split(os.path.realpath(__file__))[0] #建議使用
print file_path
==> c:/a/b/c/
print os.path.abspath("%s/../" % __file__)
此處跳到:c:/a/b/c
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
總結:所以要么不加 './' 或者"/",要么中間的路徑不能出現'/'開頭,合並路徑感覺是檢查了根目錄'/'的位置.
還是讓自動加上'/'就行