Possible Duplicate:
os.path.dirname(__file__) returns empty
A user of a Python script of mine said they got the following error:
Traceback (most recent call last):
File "MCManager.py", line 7, in <module>
os.chdir(os.path.dirname(__file__))
OSError: [Errno 2] No such file or directory: ''
How could the directory the script is in not exist? Is it a compatibility issue? I use the same OS and version as the one with the error, and haven't been able to replicate this.
Easy:
wim@wim-zenbook:~$ echo "print __file__" > /tmp/spam.py
wim@wim-zenbook:~$ python /tmp/spam.py
/tmp/spam.py
wim@wim-zenbook:~$ cd /tmp
wim@wim-zenbook:/tmp$ python spam.py
spam.py
One solution is to use os.path.abspath(__file__)
, e.g.
wim@wim-zenbook:~$ cat /tmp/spam.py
import os
print __file__
print os.path.dirname(__file__)
print os.path.dirname(os.path.abspath(__file__))
wim@wim-zenbook:~$ python /tmp/spam.py
/tmp/spam.py
/tmp
/tmp
wim@wim-zenbook:~$ cd /tmp
wim@wim-zenbook:/tmp$ python /tmp/spam.py
/tmp/spam.py
/tmp
/tmp
wim@wim-zenbook:/tmp$ python spam.py
spam.py
/tmp