美文网首页
Python中的__file__

Python中的__file__

作者: ikaroskun | 来源:发表于2017-11-08 14:39 被阅读992次

转自Python中os.path.dirname(file)的用法

在Python项目中,经常会获取文件的路径。经常会见到如下的语句:

import os
os.path.dirname(__file__)

那么这里的__file__是什么用呢?

其实就是当前脚本运行的路径。

但是也会分不同的情况。

如果执行命令时使用绝对路径,__file__就是脚本的绝对路径。

如果使用的是相对路径,__file__就是脚本的相对路径。

注:

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

In [2]: import os

In [3]: print os.path.dirname(__file__)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-b4616cfaa58d> in <module>()
----> 1 print os.path.dirname(__file__)

NameError: name '__file__' is not defined

相关文章

网友评论

      本文标题:Python中的__file__

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