23

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?

Matt Phillips
  • 11,249
  • 10
  • 46
  • 71
  • Hmm. This could be a permissions error, or the working directory for the CGI might not be the same as your python interpreter. The exact error message might help. Also, in your CGI, try `print os.getcwd()` and see what that says. – Jason Orendorff Dec 07 '10 at 21:09
  • Is your CGI script running in a chroot jail? If so, then this won't work since you can't escape from the jail. – Adam Rosenfield Dec 07 '10 at 21:15
  • @ Adam Rosenfield no. @Jason I literally run the python interpreter in the cgi-bin directory so I don't understand how it would work in that one and not inside the script that is running in the cgi-bin directory. – Matt Phillips Dec 07 '10 at 21:29
  • The above worked for me in combination with this post http://stackoverflow.com/a/3283336/706798 – Anton Jun 11 '13 at 23:36

2 Answers2

53

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.

Asger Weirsøe
  • 350
  • 1
  • 11
terminus
  • 13,745
  • 8
  • 34
  • 37
6

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")
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306