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

如何在Windows和Python 2.7上模拟os.path.samefile行为?,python,filesystems,Python,Filesystems,给定两条路径,我必须比较它们是否指向同一个文件。在Unix中,这可以通过os.path.samefile完成,但正如文档所述,它在Windows中不可用。 模拟此功能的最佳方法是什么? 它不需要模仿普通情况。在我的例子中,有以下简化: 路径不包含符号链接 文件位于同一本地磁盘中 现在我使用以下方法: def samefile(path1, path2) return os.path.normcase(os.path.normpath(path1)) == \ o

给定两条路径,我必须比较它们是否指向同一个文件。在Unix中,这可以通过
os.path.samefile
完成,但正如文档所述,它在Windows中不可用。 模拟此功能的最佳方法是什么? 它不需要模仿普通情况。在我的例子中,有以下简化:

  • 路径不包含符号链接
  • 文件位于同一本地磁盘中
现在我使用以下方法:

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

可以吗?

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

def samefile(file1, file2):
    return os.stat(file1) == os.stat(file2)
根据说明,os.path.samefile和os.path.sameopenfile现在都在py3k中。我在Python 3.3.0上验证了这一点

对于较早版本的Python,有一种使用函数的方法:


os.path.samefile的实际用例不是符号链接,而是硬链接<如果
a
b
都是指向同一文件的硬链接,则code>os.path.samefile(a,b)返回True。它们可能没有相同的路径

我知道这是一个迟来的答案。但是我在Windows上使用python,今天遇到了这个问题,找到了这个线程,发现
os.path.samefile
不适合我

因此,为了回答这个问题,
现在来模拟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对此进行了测试。

>os.path.normcase(os.path.normpath(r“c:\users\aayoubi\desktop”)“c:\\users\\aayoubi\\desktop”
我找不到失败的情况。我只找到了一个例子。”c:\\one\two'和'c:\\one\two\'可以指向同一个目录,但是这个方法会说它们是不同的。两个输出都是相同的:
>>os.path.normcase(os.path.normpath(r“c:\\one\two”))'c:\\one\\two'
>os.path.normcase(r“c:\\one\two\\”)c:\\one\\two'
Hmm,你说得对。谢谢。您需要能够处理网络路径吗?e、 g.(\\127.0.0.1\c$\test相当于c:\test)我想在两次调用stat之间修改文件在技术上是可能的。像他在问题中那样比较路径不会有这个问题是的,对于随机文件,这样的机会非常小。但我有一大堆半自动创建的文件,其中许多文件都有相同的大小和时间戳。我认为这种方法可能会导致难以发现的bug。例如,当一个架构师解包了许多具有相同时间戳的文件时,就会出现这种情况。如果它们是零字节文件,那么最终可能会出现大量错误匹配…我相信这就是
samefile
的基本实现方式。只需比较
st_dev
st_ino
就可以知道它们是否是同一个文件。