【发布时间】:2026-01-09 13:15:02
【问题描述】:
如何在 Python 中检查两个文件路径是否指向同一个文件?
【问题讨论】:
如何在 Python 中检查两个文件路径是否指向同一个文件?
【问题讨论】:
$ touch foo
$ ln -s foo bar
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> help(os.path.samefile)
Help on function samefile in module posixpath:
samefile(f1, f2)
Test whether two pathnames reference the same actual file
>>> os.path.samefile("foo", "bar")
True
【讨论】:
os.stat('foo') == os.stat('bar')来近似行为
您想使用os.path.abspath(path) 标准化每个路径以进行比较。
os.path.abspath(foo) == os.path.abspath(bar)
【讨论】:
一个简单的字符串比较应该可以工作:
import os
print os.path.abspath(first) == os.path.abspath(second)
感谢 Andrew,他更正了我最初的帖子,其中包括对 os.path.normpath 的调用:这是不需要的,因为 os.path.abspath 的实现会为您完成。
【讨论】:
normpath。
在 Windows 系统上,没有samefile 功能,您还必须担心大小写。来自os.path 的normcase 函数可以与abspath 组合来处理这种情况。
from os.path import abspath, normcase
def are_paths_equivalent(path1, path2):
return normcase(abspath(path1)) == normcase(abspath(path2))
这将认为“C:\SPAM\Eggs.txt”等同于 Windows 上的“c:\spam\eggs.txt”。
请注意,与samefile 不同,所有基于规范化和比较路径的方法都不会意识到完全不同的路径引用同一文件的情况。在 Windows 上,这意味着如果您使用 SUBST、MKLINK 或挂载的网络共享来为同一个文件创建多个不同的路径,这些解决方案都不能说“这是同一个文件”。希望大多数时候这不是什么大问题。
【讨论】:
可能有人可以在 Windows 上使用 os.path.relpath(path1, path2) 作为 os.path.samefile(path1, path2) 的解决方法吗?
如果 os.path.relpath(path1, path2) 返回 '.'比 path1 和 path2 指向同一个地方
【讨论】: