在Python中的相对位置打开文件

2024-04-26 17:55:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设python代码是在以前的windows目录(比如main)不知道的地方执行的,并且当代码运行时,无论安装在哪里,它都需要访问目录“main/2091/data.txt”。

如何使用打开(位置)功能?地点应该是什么?

编辑:

我发现下面的简单代码可以工作..它有什么缺点吗?

    file="\2091\sample.txt"
    path=os.getcwd()+file
    fp=open(path,'r+');

Tags: samplepath代码功能目录txt编辑data
3条回答

此代码工作正常:

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__)
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

要使用此方法(以及我最终如何使其工作),必须从路径末尾删除脚本名:

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_文件路径(在本例中)变为:/path/to/dir/2091/data.txt

对于这种类型的东西,你需要注意你的实际工作目录是什么。例如,不能从文件所在的目录运行脚本。在这种情况下,不能只使用相对路径本身。

如果您确定所需文件位于脚本实际所在的子目录中,则可以使用__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)

相关问题 更多 >