__file__ 变量是什么意思/做什么? [英] what does the __file__ variable mean/do?
问题描述
import os
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
模块,以便我可以开始使用它.
I usually just hard-wire these with the actual path. But there is a reason for these statements that determine path at runtime, and I would really like to understand the os.path
module so that I can start using it.
推荐答案
当从 Python 中的文件加载模块时,__file__
被设置为其路径.然后,您可以将其与其他函数一起使用以查找文件所在的目录.
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
一次举一个例子:
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.
您可以在此处查看从这些返回的各种值:
You can see the various values returned from these here:
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
等)运行它,看看有什么不同
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
这篇关于__file__ 变量是什么意思/做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!