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?
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?
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.path[0]
, and either chdir
to it or use it directly in the filename:
os.path.join(sys.path[0], '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