假设我的python代码是在一个名为main的目录中执行的,并且应用程序需要访问main/2091/data.txt。
我应该如何使用open(location)?参数location应该是什么?
编辑:
我发现下面的简单代码可以工作。它有什么缺点吗?
file = "\2091\sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');发布于 2011-08-24 02:59:32
在这种情况下,你需要注意你的实际工作目录是什么。例如,您可能无法从文件所在的目录运行脚本。在这种情况下,您不能只使用相对路径本身。
如果您确定所需的文件位于脚本实际所在的子目录中,则可以使用__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)发布于 2015-10-06 23:06:37
下面的代码运行良好:
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)发布于 2014-09-02 04:54:44
我创建了一个帐户,只是为了澄清我在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
https://stackoverflow.com/questions/7165749
复制相似问题