Answers:
从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
等等)运行它,以了解有什么不同。
name '__file__' is not defined
。
__file__
是从中加载模块的文件的路径名(如果它是从文件加载的)。这意味着__file__
仅当您将其作为脚本运行在解释器中时才起作用。(除非您将其导入解释器...)
我只想先解决一些困惑。 __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
__file__
并非在所有情况下都已定义,例如静态链接的C模块。我们不能指望__file__
总是有空。