__file__变量的含义/作用是什么?


177
A = os.path.join(os.path.dirname(__file__), '..')

B = os.path.dirname(os.path.realpath(__file__))

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

我通常只是将这些与实际路径固定在一起。但是这些语句在运行时确定路径是有原因的,我真的很想了解os.path模块,以便可以开始使用它。

Answers:


162

从Python中的文件加载模块时,__file__将设置为其路径。然后,可以将其与其他功能一起使用,以查找文件所在的目录。

一次举一个例子:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

您可以在此处查看从这些返回的各种值:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

并确保您从不同的位置(例如./text.py~/python/text.py等等)运行它,以了解有什么不同。


7
好的答案,但请从其他答案中了解其他重要细节:__file__并非在所有情况下都已定义,例如静态链接的C模块。我们不能指望__file__总是有空。
克里斯·约翰逊

5
在解释器中,所有示例均返回name '__file__' is not defined
user1063287 2014年

10
@ user1063287查看DemoUser的答案;__file__是从中加载模块的文件的路径名(如果它是从文件加载的)。这意味着__file__仅当您将其作为脚本运行在解释器中时才起作用。(除非您将其导入解释器...)
YOUNG

59

我只想先解决一些困惑。 __file__不是通配符,而是一个属性。根据惯例,双下划线属性和方法被认为是“特殊的”,并具有特殊的用途。

http://docs.python.org/reference/datamodel.html展示了许多特殊方法和属性(如果不是全部的话)。

在这种情况下,__file__是模块(模块对象)的属性。在Python中,.py文件是一个模块。因此import amodule将具有一个属性,__file__该属性表示在不同情况下的不同事物。

来自文档:

__file__是从中加载模块的文件的路径名(如果它是从文件加载的)。__file__对于静态链接到解释器的C模块,该属性不存在。对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

在您的情况下,模块正在__file__全局命名空间中访问其自己的属性。

要查看实际效果,请尝试:

# file: test.py

print globals()
print __file__

并运行:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

23

根据文档

__file__是从中加载模块的文件的路径名(如果它是从文件加载的)。__file__对于静态链接到解释器的C模块,该属性不存在。对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

__file__除非模块是内置的(并因此在sys.builtin_module_names中列出),否则它将成为文件的“路径”,在这种情况下,未设置属性。


13

使用__file__具有各种组合的os.path模块允许所有路径是相对的当前模块的目录位置。这使您的模块/项目可以移植到其他机器上。

在您的项目中,您需要执行以下操作:

A = '/Users/myname/Projects/mydevproject/somefile.txt'

然后尝试使用部署目录将其部署到您的服务器,例如/home/web/mydevproject/您的代码将无法正确找到路径。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.