在Python中以相对路径打开文件
假设我的Python代码是在一个叫做 main
的文件夹里运行的,而这个应用需要访问 main/2091/data.txt
这个文件。
我应该怎么用 open(location)
来打开这个文件呢?那里的参数 location
应该是什么?
我发现下面这段简单的代码可以正常工作……这样做有什么缺点吗?
file = "\2091\sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');
14 个回答
35
我注册了一个账号,就是想澄清一下我在Russ的原回答中发现的一个小问题。
为了方便大家参考,他的原回答是:
import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
这个回答很棒,因为它试图动态地创建一个指向目标文件的绝对路径。
Cory Mawhorter注意到,__file__
是一个相对路径(在我的系统上也是这样),于是建议使用os.path.abspath(__file__)
。不过,os.path.abspath
返回的是你当前脚本的绝对路径(也就是说,像/path/to/dir/foobar.py
这样的路径)。
要使用这个方法(也是我最后让它工作的方式),你需要从路径的末尾去掉脚本的名字:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
在这个例子中,得到的abs_file_path变成了:/path/to/dir/2091/data.txt
54
这段代码运行得很好:
import os
def read_file(file_name):
file_handle = open(file_name)
print file_handle.read()
file_handle.close()
file_dir = os.path.dirname(os.path.realpath('__file__'))
print file_dir
#For accessing the file in the same folder
file_name = "same.txt"
read_file(file_name)
#For accessing the file in a folder contained in the current folder
file_name = os.path.join(file_dir, 'Folder1.1/same.txt')
read_file(file_name)
#For accessing the file in the parent folder of the current folder
file_name = os.path.join(file_dir, '../same.txt')
read_file(file_name)
#For accessing the file inside a sibling folder.
file_name = os.path.join(file_dir, '../Folder2/same.txt')
file_name = os.path.abspath(os.path.realpath(file_name))
print file_name
read_file(file_name)
280
在这种情况下,你需要注意你当前的工作目录是什么。比如说,你可能并不是在文件所在的目录下运行这个脚本。在这种情况下,你不能单单依靠相对路径。
如果你确定你想要的文件在脚本实际所在目录的一个子目录下,你可以使用 __file__
来帮你解决这个问题。 __file__
是你正在运行的脚本的完整路径。
所以你可以尝试像这样操作:
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)