今天在命令行想使用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__
并未生成。
补基础知识:
- __file__是当前脚本运行的路径。但是也会分不同的情况。
- 如果执行命令时使用绝对路径,__file__就是脚本的绝对路径。
- 如果使用的是相对路径,__file__就是脚本的相对路径。
- os.path.dirname()
os.path.dirname(path) 返回path的目录。