Issue
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.
Solution
It happens in Python 2 when executing a script from the same directory, e.g.
$ echo "print __file__" > /tmp/spam.py
$ python /tmp/spam.py
/tmp/spam.py
$ cd /tmp
$ python spam.py
spam.py
One solution is to use os.path.abspath(__file__)
in the code, so that you can always resolve the script directory in all three usage cases below:
$ cat /tmp/spam.py
import os
print os.path.dirname(os.path.abspath(__file__))
$ python /tmp/spam.py
/tmp
$ cd /tmp
$ python /tmp/spam.py
/tmp
$ python spam.py
/tmp
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.