filecmp()
的 Python 2 文档说:
Unless shallow is given and is false, files with identical
os.stat()
signatures are taken to be equal.
这听起来像是两个文件,除了它们的 os.stat()
签名外都相同,将被认为是不相等的,但情况似乎并非如此,如运行以下代码片段所示:
import filecmp
import os
import shutil
import time
with open('test_file_1', 'w') as f:
f.write('file contents')
shutil.copy('test_file_1', 'test_file_2')
time.sleep(5) # pause to get a different time-stamp
os.utime('test_file_2', None) # change copied file's time-stamp
print 'test_file_1:', os.stat('test_file_1')
print 'test_file_2:', os.stat('test_file_2')
print 'filecmp.cmp():', filecmp.cmp('test_file_1', 'test_file_2')
输出:
test_file_1: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0,
st_uid=0, st_gid=0, st_size=13L, st_atime=1320719522L, st_mtime=1320720444L,
st_ctime=1320719522L)
test_file_2: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0,
st_uid=0, st_gid=0, st_size=13L, st_atime=1320720504L, st_mtime=1320720504L,
st_ctime=1320719539L)
filecmp.cmp(): True
如您所见,这两个文件的时间戳 - st_atime
、st_mtime
和 st_ctime
- 显然不相同,但是 filecmp.cmp()
表示两者相同。我是不是误解了什么,或者 filecmp.cmp()
的实现或其文档中是否存在错误?
更新
Python 3 documentation已经重新措辞,目前说了以下内容,恕我直言,这只是在更好地暗示即使 shallow
为 True 时,具有不同时间戳的文件仍可能被视为相等的意义上的改进。
If shallow is true, files with identical
os.stat()
signatures are taken to be equal. Otherwise, the contents of the files are compared.
FWIW 我认为简单地说这样的话会更好:
If shallow is true, file content is compared only when
os.stat()
signatures are unequal.
最佳答案
您误解了文档。第 2 行说:
Unless shallow is given and is false, files with identical
os.stat()
signatures are taken to be equal.
具有相同 os.stat()
签名的文件被认为是相等的,但是 logical inverse不正确:具有不相等 os.stat()
签名的文件不一定被视为不相等。相反,它们可能不相等,在这种情况下比较实际的文件内容。由于发现文件内容相同,filecmp.cmp()
返回 True
。
根据第三条,一旦确定文件相等,它将缓存该结果,如果您要求它再次比较相同的文件,它不会重新读取文件内容,只要那些文件的 os.stat
结构不会改变。
关于python - filecmp.cmp() 忽略不同的 os.stat() 签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045564/