给定两个路径,我必须比较它们是否指向同一个文件。在 Unix 中,这可以使用
os.path.samefile
来完成,但正如文档所述,它在 Windows 中不可用。
模拟此功能的最佳方法是什么?
它不需要模拟常见情况。就我而言,有以下简化:
现在我使用以下内容:
def samefile(path1, path2)
return os.path.normcase(os.path.normpath(path1)) == \
os.path.normcase(os.path.normpath(path2))
这样可以吗?
根据 issue#5985 os.path.samefile 和 os.path.sameopenfile 现在位于 py3k 中。我在Python 3.3.0上验证了这一点
对于旧版本的 Python,这里有一种使用 GetFileInformationByHandle 函数的方法:
os.stat 系统调用返回一个元组,其中包含有关每个文件的大量信息 - 包括创建和上次修改时间戳、大小、文件属性。不同文件具有相同参数的可能性非常小。我觉得这样做是非常合理的:
def samefile(file1, file2):
return os.stat(file1) == os.stat(file2)
os.path.samefile
的真正用例不是符号链接,而是硬链接。如果 os.path.samefile(a, b)
和 a
都是指向同一文件的硬链接,则 b
返回 True。他们的道路可能并不相同。
我知道这是这个帖子中较晚的答案。但我在 Windows 上使用 python,今天遇到了这个问题,找到了这个线程,发现
os.path.samefile
对我不起作用。
所以,回答OP,
now to emulate os.path.samefile
,这就是我模仿它的方式:
# because some versions of python do not have os.path.samefile
# particularly, Windows. :(
#
def os_path_samefile(pathA, pathB):
statA = os.stat(pathA) if os.path.isfile(pathA) else None
if not statA:
return False
statB = os.stat(pathB) if os.path.isfile(pathB) else None
if not statB:
return False
return (statA.st_dev == statB.st_dev) and (statA.st_ino == statB.st_ino)
它并不是越紧越好,因为我更感兴趣的是清楚我在做什么。
我在 Windows-10 上使用 python 2.7.15 进行了测试。
注意事项:
st_ino
和 st_dev
并不总是有有意义的内容。st_ino
始终为 0。