If I Change The Current Working Directory, Why Does __file__ Become Invalid Path?
Executing test.py from /tmp import os print os.path.abspath(__file__) os.chdir('/var') print os.path.abspath(__file__) output: /tmp/test.py /var/test.py I expected the second ou
Solution 1:
Depending on how you invoke the python script, __file__
can be an absolute or a relative path (e.g. python /tmp/test.py
for the former and cd /tmp; python test.py
for the latter).
So if __file__
is relative, os.path.abspath
will use the current working directory as the base directory.
Easy to prove by adding print __file__
to your test script.
Post a Comment for "If I Change The Current Working Directory, Why Does __file__ Become Invalid Path?"