Take the 2-minute tour ×
import os
print __file__
print os.path.dirname(__file__)
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__)
print os.path.abspath(__file__)

the output is like this :

wim@wim-acer:~$ python --version
Python 2.7.1+
wim@wim-acer:~$ pwd
wim@wim-acer:~$ python /home/wim/spam.py
wim@wim-acer:~$ python ./spam.py
share|improve this question
Can't reproduce on Windows 7, Python 2.6.2. Does the directory switched to matter, or does any directory do this? Must the file be imported, or can it be run stand-alone? What Python version are you using? How exactly is it "broken" the second time (what isn't as expected)? –  Cameron Jul 28 '11 at 2:32
"What is the usual mechanism for working around this"? What? Why do you what the absolute path to __file__? Why are you waiting until after you do "not know where/when/how os.chdir may have been called previously" to get the absolute path? –  S.Lott Jul 28 '11 at 2:33
sorry , the reason is for use in a debug helper function. i use inspect module to get a bunch of other information , so that instead of littering code with 'print i', for example, i could use dbgp('i') and get a differently coloured line of output like /abs/path/to_file.py:line_number i = repr(i) –  wim Jul 28 '11 at 3:36
@Cameron , i apologize i wasn't very clear in my first example. i have answered your questions in the second edit. –  wim Jul 28 '11 at 4:10
So is your ultimate goal a nicer/better debug output? –  Keith Jul 28 '11 at 4:22
show 1 more comment

2 Answers

up vote 1 down vote accepted

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
share|improve this answer
could not the same filename in __file__ exist in sys.path multiple times? –  wim Jul 28 '11 at 3:31
@wim: Yes. It could. So? Python searches sys.path in order when it loads. You're searching in the same order. –  S.Lott Jul 28 '11 at 9:41
this is mostly correct. however, there is a special case where __file__ was an absolute path, and os.path.exists(dirname,__file__) returns True because dirname, from sys.path[0], was '' (the empty string). –  wim Aug 5 '11 at 4:13
add comment

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.

share|improve this answer
add comment

Your Answer


