Python os module open file above current directory with relative path

蓝咒 提交于 2019-11-27 11:41:29

问题


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.

/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 CAN do this?


回答1:


The path given to open should 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.

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.path will take care of the details of joining the two paths.




回答2:


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


来源:https://stackoverflow.com/questions/4381569/python-os-module-open-file-above-current-directory-with-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!