获取包含Python文件的目录的完整路径
问题描述:
实际上,我从前面的回答中找到了我的主要问题“获取Python文件所在目录的完整路径”的解决方案:Find current directory and file's directory。获取包含Python文件的目录的完整路径
如果我运行我的整个脚本,换句话说,热键F5,答案的下面的代码运行良好。
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
但是,如果我只是选择上述代码的两行并运行它,换句话说,热键F9。然后,我会收到以下错误:
NameError: name '__file__' is not defined
所以,如果有人碰巧知道为何出现错误,请给出一个简要的解释。
非常感谢!
顺便说一句,我用Spyder(Python 2.7)。
答
在Spyder或任何交互式python过程中,常量__file__
未定义。
当你运行整个脚本,Spyder的基本运行以下命令:
$ python script.py
同时,如果您选择了这两行,它更像是第一次进入一个交互式的Python程序,然后解释语句:
$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>>
这就是区别。
谢谢!现在清除。 – zlpython