os.path.dirname(__file__) doesn't exist? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-12 04:36:02

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/12882144/os-path-dirname-file-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!