Python os模块使用相对路径打开当前目录上方的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4381569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:30:44  来源:igfitidea点击:

Python os module open file above current directory with relative path

pythonfile-iocgicgi-bin

提问by Matt Phillips

The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this.

OS 模块的文档似乎没有关于如何打开不在子目录或脚本运行的当前目录中的文件而没有完整路径的信息。我的目录结构是这样的。

/home/matt/project/dir1/cgi-bin/script.py
/home/matt/project/fileIwantToOpen.txt

open("../../fileIwantToOpen.txt","r")

Gives a file not found error. But if I start up a python interpreter in the cgi-bin directory and try open("../../fileIwantToOpen.txt","r")it works. I don't want to hard code in the full path for obvious portability reasons. Is there a set of methods in the OS module that CANdo this?

给出一个找不到文件的错误。但是如果我在 cgi-bin 目录中启动一个 python 解释器并尝试open("../../fileIwantToOpen.txt","r")它的工作。出于明显的可移植性原因,我不想在完整路径中进行硬编码。有一组的OS模块的方法是CAN做到这一点?

采纳答案by terminus

The path given to openshould be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory.

给定的路径open应该相对于当前工作目录,即运行脚本的目录。所以上面的例子只有在你从 cgi-bin 目录运行时才有效。

A simple solution would be to make your path relative to the script. One possible solution.

一个简单的解决方案是使您的路径相对于脚本。一种可能的解决方案。

from os import path

basepath = path.dirname(__file__)
filepath = path.abspath(path.join(basepath, "..", "..", "fileIwantToOpen.txt"))
f = open(filepath, "r")

This way you'll get the path of the script you're running (basepath) and join that with the relative path of the file you want to open. os.pathwill take care of the details of joining the two paths.

通过这种方式,您将获得正在运行的脚本的路径 (basepath),并将其与您要打开的文件的相对路径连接起来。os.path将处理加入两条路径的细节。

回答by Andrew Clark

This should move you into the directory where the script is located, if you are not there already:

这应该将您移动到脚本所在的目录中,如果您还没有:

file_path = os.path.dirname(__file__)
if file_path != "":
    os.chdir(file_path)
open("../../fileIwantToOpen.txt","r")