在Python中打开相对位置的文件
在Python中,打开相对位置的文件是一个常见的问题。在这个问题中,原始回答中存在一个错误,Cory Mawhorter提出了一个更好的解决方法。
原始回答中使用了以下代码来动态创建所需文件的绝对系统路径:
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`。
您甚至可以结合这两种方法来简化代码:
import os abs_file_path = os.path.dirname(os.path.abspath(__file__)) + "/2091/data.txt"
这样做比尝试自己复制`os.path.dirname`的功能要好,正如我去年的回答中所做的那样。
在Python中打开相对路径的文件
在Python中,我们经常需要打开并操作文件。通常情况下,我们可以通过提供文件的绝对路径来打开文件。但是,有时候我们可能需要打开相对于当前运行脚本的位置的文件。这就引发了一个问题:如何在Python中打开相对路径的文件?
在下面的代码中,我们可以看到一个简单的例子,展示了如何在Python中打开相对路径的文件:
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)
然而,有些人在尝试使用`../`来访问当前文件夹的父文件夹中的文件时,遇到了问题。在Windows系统上,Python报错说找不到文件,并且路径中显示的是使用了`\\`作为分隔符。另外,在Ubuntu系统和Python 3中,某些情况下需要去掉`'__file__'`中的引号。
为了解决这个问题,有几种方法可以尝试:
1. 使用`os.path.join`函数来构建文件路径,这样就不需要手动添加`/`或`\`作为分隔符。例如:`os.path.join(path, 'folderA', 'file.txt')`。
2. 使用`__file__`而不是`'__file__'`来获取当前脚本的路径。正确的写法是`file_dir = os.path.dirname(os.path.realpath(__file__))`。
通过采用这些解决方法,我们可以在Python中成功打开相对路径的文件,而不受操作系统或Python版本的限制。
在Python中打开相对位置的文件
在Python中打开文件时,需要注意当前的工作目录。例如,您可能不是从文件所在的目录运行脚本。在这种情况下,您不能仅仅使用相对路径。
如果您确定所需的文件在脚本所在的子目录中,可以使用__file__
来帮助您解决问题。__file__
是正在运行的脚本的完整路径。
你可以尝试以下代码:
import os script_dir = os.path.dirname(__file__) # 脚本所在的绝对路径 rel_path = "2091/data.txt" # 文件相对路径 abs_file_path = os.path.join(script_dir, rel_path) # 文件的绝对路径
我发现以下简单代码可以工作...它有什么缺点吗?
file = "\sample.txt" path = os.getcwd() + str(loc) + file fp = open(path, 'r+')
这种方法的缺点是当前工作目录(cwd)可能是任何位置,而不一定是脚本所在的位置。而__file__
是一个相对路径(至少在我的设置中是这样),您需要先调用os.path.abspath(__file__)
。在osx/homebrew 2.7上测试通过。
对于Python 2.7,os.path.dirname(file)
对我来说不起作用。它显示NameError: name '__file__' is not defined
。
我认为您是在控制台中尝试它。请在*.py文件中尝试。
在2091/data.txt
中,你不应该使用os.path.join
吗?在Windows中会有问题吗?\` &
/`