Under certain circumstances, the variable __file__
is relative (see this stackoverflow question for details). If the variable is relative and one changes the current working directory, __file__
doesn't change accordingly. As a result, the relative path is invalid.
Please see this minimal example:
import os
if __name__ == '__main__':
filepath = __file__
filepath_real = os.path.realpath(filepath)
print('pwd', os.getcwd())
print('relative', filepath, os.path.exists(filepath))
print('absolute', filepath_real, os.path.exists(filepath_real))
os.chdir('..')
print('... changing the working directory ...')
filepath = __file__
filepath_real = os.path.realpath(filepath)
print('pwd', os.getcwd())
print('relative', filepath, os.path.exists(filepath))
print('absolute', filepath_real, os.path.exists(filepath_real))
Suppose this file is located at /home/user/project/script.py
. If I execute script.py
, this is the output:
$ cd /home/user/project/
$ python script.py
pwd /home/user/project
relative test.py True
absolute /home/user/project/test.py True
... changing the working directory ...
pwd /home/user
relative test.py False
absolute /home/user/test.py False
Is it possible to get a correct __file__
path (one that exists according to os.path.exists
) after changing the working directory in Python 3.7? I am aware that this issue does not exist in higher Python versions (such as 3.9), where __file__
always returns an absolute path.