os.path.dirname(__file__) 不存在吗? [英] os.path.dirname(__file__) doesn't exist?
本文介绍了os.path.dirname(__file__) 不存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
os.path.dirname(__file__) 返回空
我的一个 Python 脚本的用户说他们收到了以下错误:
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.
推荐答案
简单:
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
一种解决方案是使用os.path.abspath(__file__)
,例如
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
这篇关于os.path.dirname(__file__) 不存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文