python - filecmp.cmp() 忽略不同的 os.stat() 签名?

标签 python file-comparison

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_atimest_mtimest_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/

相关文章:

python - 一起计算注释字段

android - 通过移动数据发送 POST 请求

C中的跨平台网络二进制文件比较?

php - 如何使用 php 比较两个文件来找到多余的行?

diff - 什么工具可以对同一文件中的两个部分进行视觉比较?

python - 应该如何实现对 twisted.pb 中备用凭证类型的支持?

python - 在 matplotlib 中绘制方形等高线图

python - 在带有色调(分类变量)的pairgrid图上显示两个相关系数 - seaborn python

command-line - 通过命令行在现有 meld 实例中打开新选项卡

python - 相互匹配两个文件并将输出写入文件 - Python