问题解决:NameError: name '__file__' is not defined

今天在命令行想使用os.path.dirname查看文件路径时遇到这个问题:

>>> import os
>>> print(os.path.dirname(__file__))

报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

错误原因:
如果在交互式环境中,则会爆出异常。因为此时__file__并未生成。


补基础知识:

  1. __file__是当前脚本运行的路径。但是也会分不同的情况。
    • 如果执行命令时使用绝对路径,__file__就是脚本的绝对路径。
    • 如果使用的是相对路径,__file__就是脚本的相对路径。
  2. os.path.dirname()
    os.path.dirname(path) 返回path的目录。
发布了673 篇原创文章 · 获赞 644 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/103816033