views:

132

answers:

4

For instance, if I have:
C:\42\main.py
and
C:\42\info.txt
and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt".

Is it supposed to be like that?
If not, how can I fix it?

+3  A: 

It is supposed to be like that. Relative paths are relative to the process's current working directory, not the directory that your script resides in.

Laurence Gonsalves
+1  A: 

Rather than hardcoding it, you can find the script's path using sys.path[0], and either chdir to it or use it directly in the filename:

os.path.join(sys.path[0], 'info.txt')
Michael Mrozek
sys.path[0] returns the path of the script that was called from command line. It will not work for scripts imported from a different directory.
Brendan Abel
+7  A: 

You can specify paths relative to where your script is. I do it all the time when writing unittests.

Every python file has a special attribute -- __file__ -- that stores the path to that file.

py_file= os.path.abspath(__file__) # path to main.py
py_dir = os.path.dirname(py_file) # path to the parent dir of main.py
txt_file = os.path.join(py_dir, 'info.txt') # path to info.txt
Brendan Abel
Whoa, that was fast! Thanks!
Gerardo Marset
A: 

or you could make the entire thing more flexible by using command line arguments..