Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os module open file above current directory with relative path

Tags:

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?

like image 239
Matt Phillips Avatar asked Dec 07 '10 21:12

Matt Phillips


People also ask

How do you pass a relative path in Python?

relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.

How do I open a file in a specific directory in Python?

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys. path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.

What is relative path in Python?

A relative file path is interpreted from the perspective your current working directory. If you use a relative file path from the wrong directory, then the path will refer to a different file than you intend, or it will refer to no file at all.


1 Answers

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.

like image 145
terminus Avatar answered Sep 19 '22 14:09

terminus