NameError: name '__file__' is not defined

NameError: name '__file__' is not defined

我正在尝试使用以下方法将脚本路径存储到变量中:

os.path.abspath(os.path.dirname(__file__))

但是,它一直返回 name '__file__' is not defined 错误。

here = os.path.dirname(os.path.abspath(__file__))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

很确定您是 运行 在交互式 Python 的终端中,因为这是唯一(我知道)没有 __file__ 的地方。此外,如果它是一个脚本,并且它将是它的第一行(根据错误消息),它将在 os is not defined 上失败(因为您不会导入它)。

在实际脚本中尝试。这应该有效。

我 运行 在 Spyder 中 测试/调试 类 时(几乎每天)。修复很简单:将 __file__ 变量定义为您正在测试的 py 模块的名称。

在解释器中输入:

__file__ = 'modulename.py'

然后 运行 脚本再次出现。这种方法从未对我造成问题。