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.
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.
Whoa, that was fast! Thanks! – Gerardo Marset Apr 11 '10 at 1:09.
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.
Rather than hardcoding it, you can find the script's path using sys. Path0, and either chdir to it or use it directly in the filename: os.path. Join(sys.
Path0, 'info. Txt').
Sys. Path0 returns the path of the script that was called from command line. It will not work for scripts imported from a different directory.
– Brendan Apr 11 '10 at 0:17.