wim
wim

Reputation: 362507

__file__ and os.path module not playing nicely?

import os
print __file__
print os.path.dirname(__file__)
os.chdir('/tmp')
print __file__  # unchanged, of course
print os.path.dirname(__file__)  # now broken

I have this issue above where dirname(__file__) can no longer be relied upon after os.chdir has been used in the script, after module loader has set __file__.

What is the usual mechanism for working around this, assuming you may not know where/when/how os.chdir may have been called previously?

edit: i hope this second example can better clarify my issue

import os
old_dir = os.getcwd()
print os.path.abspath(__file__)
os.chdir('/tmp')
print os.path.abspath(__file__)
os.chdir(old_dir)

the output is like this :

wim@wim-acer:~$ python --version
Python 2.7.1+
wim@wim-acer:~$ pwd
/home/wim
wim@wim-acer:~$ python /home/wim/spam.py
/home/wim/spam.py
/home/wim/spam.py
wim@wim-acer:~$ python ./spam.py
/home/wim/spam.py
/tmp/spam.py

Upvotes: 4

Views: 1456

Answers (2)

Keith
Keith

Reputation: 43024

The last example has a relative path element in the __file__ name (./xxx.py). When abspath is called with that it is expanded to the current directory.

If you put this code in a module you won't have that issue.

Upvotes: 1

S.Lott
S.Lott

Reputation: 391818

The __file__ must exist in sys.path somewhere.

for dirname in sys.path:
   if os.path.exists( os.path.join(dirname,__file__) ):
       # The directory name for `__file__` was dirname

Upvotes: 1

Related Questions