简体   繁体   English

Python os模块在当前目录上打开文件,具有相对路径

[英]Python os module open file above current directory with relative path

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. OS模块的文档似乎没有关于如何在没有完整路径的情况下打开不在子目录中的文件或脚本运行的当前目录的信息。 My directory structure looks like this. 我的目录结构如下所示。

/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. 但是如果我在cgi-bin目录中启动一个python解释器并尝试open("../../fileIwantToOpen.txt","r")它可以工作。 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 CAN do this? 有一组的OS模块的方法可以做到这一点?

The path given to open should be relative to the current working directory, the directory from which you run the script. open的路径应该相对于当前工作目录,即运行脚本的目录。 So the above example will only work if you run it from the cgi-bin directory. 所以上面的例子只有从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. 这样,您将获得正在运行的脚本的路径(basepath),并将其与要打开的文件的相对路径连接起来。 os.path will take care of the details of joining the two paths. os.path将负责加入这两条路径的细节。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM