美文网首页
NameError: name '__file__' is no

NameError: name '__file__' is no

作者: 写给明天的自己 | 来源:发表于2021-07-19 19:07 被阅读0次

没有钱包的充实,哪来内心的宁静,很多人都本末倒置了。

使用场景:在python的交互模式下使用file
原因分析:文件模式下,file显示文件路径,在交互模式下file显示不出来路径,所以就报错了。

错误示例:

>>> import os
>>> path = os.path.dirname(os.path.abspath(__file__))

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

直接在文件模式下这样写没有问题

import os
path = os.path.dirname(os.path.abspath(__file__))
print(path)

解决方法:
使用英文引号引上__file__,此方法可行,实际上你只要不是想要获取当前文件的绝对路径,在abspath()随便传一个字符串即可,但是在文件模式下,不要这样写,这样写就失去了__file__本身的意义。

>>> import os
>>> path = os.path.dirname(os.path.abspath('__file__'))

感兴趣的同学可以看一下另一篇关于python的__file__

python获取相对路径、绝对路径的__file__使用


如果感觉本文对您有帮助可以点个赞哦

本文为学习笔记,转载请标明出处

本文仅供交流学习,请勿用于非法途径

仅是个人意见,如有想法,欢迎留言

相关文章

网友评论

      本文标题:NameError: name '__file__' is no

      本文链接:https://www.haomeiwen.com/subject/ncjhmltx.html