Python 中的 __file__ 变量

Muhammad Maisam Abbas 2021年10月2日
Python 中的 __file__ 变量

本教程将讨论 Python 中的 __file__ 变量。

Python 中的 __file__ 变量

围绕某些变量和方法名称的双下划线在 Python 中也称为 dunder。按照惯例,名称被 dunder 包围的任何变量或方法都是特殊的变量或方法。__file__ 变量也是一个特殊变量,用于获取导入到我们代码中的任何模块的确切路径。下面的代码片段向我们展示了如何使用 __file__ 变量获取导入模块的路径。

import os
print(os.__file__)

输出:

/usr/lib/python3.7/os.py

在上面的代码中,我们使用 __file__ 特殊变量打印了包含 os 模块的文件路径;这也可以用于用户生成的模块。以下代码片段向我们展示了如何将 __file__ 变量用于用户生成的模块。

hello.py 文件:

def printHello():
    print("Hello World")

main.py 文件:

import hello as h

h.printHello()
print(h.__file__)

输出:

Hello World
/content/hello.py

在上面的代码中,我们使用 __file__ 特殊变量来获取用户生成的模块 hello 的路径。首先,我们创建了包含 printHello() 方法的 hello.py 文件,该方法在控制台中打印 Hello World

然后,我们在我们的 main.py 文件中导入了 hello 模块并调用了 h.printHello() 方法。最后,我们使用 print(h.__file__) 方法打印了包含 hello 模块的文件的路径。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn