Cory
Cory

Reputation: 15615

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 output to be /tmp/test.py. Is this a bug or expected behavior? Is there a way to get the actual location of the file that is not affect by chdir?

I am using Python 2.7

Upvotes: 0

Views: 531

Answers (1)

isedev
isedev

Reputation: 19601

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.

Upvotes: 4

Related Questions