写在前面:看大家阅读量这么大,也应该在放点干货来了~~
获取层级路径,直到可以获取文件夹下面的文件,多一个判断就行了:
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
总结:所以要么不加 './' 或者"/",要么中间的路径不能出现'/'开头,合并路径感觉是检查了根目录'/'的位置.
还是让自动加上'/'就行