__file__ 变量是什么意思/做什么?

新手上路,请多包涵
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 模块,以便我可以开始使用它。

原文由 depling 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 555
1 个回答

当从 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 等等)看看有什么不同。

原文由 paxdiablo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏