获取包含Python文件的目录的完整路径

时间:2017-06-29 13:41:54

标签: python directory os.path

实际上我找到了我的主要问题的解决方案“从上一个答案中获取包含Python文件的目录的完整路径:Find current directory and file's directory

如果我运行整个脚本,换句话说,热键F5,答案下面的代码就可以正常工作。

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

但是,如果我只选择上面两行代码并运行它,换句话说,就是热键F9。然后我会收到以下错误:

NameError: name '__file__' is not defined

因此,如果有人碰巧知道错误发生的原因,请简要说明一下。

非常感谢!

顺便说一句,我使用了Spyder(Python 2.7)。

1 个答案:

答案 0 :(得分:1)

在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
>>> 

这就是区别。