import os
def readFile(filename):
filehandle = open(filename)
print filehandle.read()
filehandle.close()
fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir
#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)
#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)
#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)
#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)
import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
此代码工作正常:
我创建了一个账户,只是为了澄清我认为在罗斯最初的回复中发现的一个差异。
作为参考,他最初的回答是:
这是一个很好的答案,因为它试图动态地创建到所需文件的绝对系统路径。
Cory Mawhoter注意到
__file__
是一个相对路径(在我的系统上也是如此),建议使用os.path.abspath(__file__)
。os.path.abspath
但是,返回当前脚本的绝对路径(即/path/to/dir/foobar.py
)要使用此方法(以及我最终如何使其工作),必须从路径末尾删除脚本名:
生成的abs_文件路径(在本例中)变为:
/path/to/dir/2091/data.txt
对于这种类型的东西,你需要注意你的实际工作目录是什么。例如,不能从文件所在的目录运行脚本。在这种情况下,不能只使用相对路径本身。
如果您确定所需文件位于脚本实际所在的子目录中,则可以使用
__file__
来帮助您完成此任务。__file__
是运行的脚本所在的完整路径。所以你可以摆弄这样的东西:
相关问题 更多 >
编程相关推荐