如何在 Windows 和 Python 2.7 上模拟 os.path.samefile 行为?

问题描述 投票:0回答:4

给定两个路径,我必须比较它们是否指向同一个文件。在 Unix 中,这可以使用

os.path.samefile
来完成,但正如文档所述,它在 Windows 中不可用。 模拟此功能的最佳方法是什么? 它不需要模拟常见情况。就我而言,有以下简化:

  • 路径不包含符号链接。
  • 文件在同一个本地磁盘。

现在我使用以下内容:

def samefile(path1, path2)
    return os.path.normcase(os.path.normpath(path1)) == \
           os.path.normcase(os.path.normpath(path2))

这样可以吗?

python filesystems
4个回答
5
投票

根据 issue#5985 os.path.samefile 和 os.path.sameopenfile 现在位于 py3k 中。我在Python 3.3.0上验证了这一点

对于旧版本的 Python,这里有一种使用 GetFileInformationByHandle 函数的方法:

查看两个文件是否是同一个文件


4
投票

os.stat 系统调用返回一个元组,其中包含有关每个文件的大量信息 - 包括创建和上次修改时间戳、大小、文件属性。不同文件具有相同参数的可能性非常小。我觉得这样做是非常合理的:

def samefile(file1, file2):
    return os.stat(file1) == os.stat(file2)

4
投票

os.path.samefile
的真正用例不是符号链接,而是链接。如果
os.path.samefile(a, b)
a
都是指向同一文件的硬链接,则
b
返回 True。他们的道路可能并不相同。


1
投票

我知道这是这个帖子中较晚的答案。但我在 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
并不总是有有意义的内容。
在 Windows10、Python 2.7.9 上观察:
st_ino
始终为 0。
请参阅旧帖子此处

© www.soinside.com 2019 - 2024. All rights reserved.