os.path.abspath 对比 os.path.dirname

os.path.abspath vs os.path.dirname

这些字符串值相等,但它们真的相等吗?哪里发生了什么?

import os

path_name1 = os.path.abspath(os.path.dirname(__file__))
path_name2 = os.path.dirname(os.path.abspath(__file__))

print(path_name1)
print(path_name2)

根据here, the value of __file__ is a string, which is set when module was imported by a loader. From here可以看出__file__的值为

The path to where the module data is stored (not set for built-in modules).

通常路径已经是模块的绝对路径。因此,您的代码的第 4 行可以简化为 path_name2 = os.path.dirname(__file__)。显然,您的代码的第 3 行可以表示为 path_name1 = os.path.abspath(path_name2)(让我们暂时忽略执行顺序)。

接下来要看dirname做了什么。事实上,您可以将 dirname 视为 os.path.split 的包装器,它将路径分为两部分:(head, tail)tail 是给定路径的最后一部分,head 是给定路径的其余部分。因此,path_name2 只是包含加载文件的目录的路径。此外, path_name2 是绝对路径。因此 os.path.abspath(path_name2)path_name2 相同。所以,path_name1path_name2 相同。