Python 2文档中filecmp()
的说明如下:
除非给定并且为假,否则具有相同
os.stat()
签名的文件被视为相等。
这听起来像是两个文件除了它们的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为真,则具有相同
os.stat()
签名的文件被视为相等。否则,比较文件的内容。FWIW,我认为最好直接说这样的话:
如果shallow为true,则仅在
os.stat()
签名不相同时比较文件内容。
cmp()
的作用了 - 我认为这与文档不一致。当给定(或默认)一个真值时,shallow
没有被尊重,因为文件只有在它们的os.stat()
签名匹配时才会被读取。在我看来,如果shallow
是真的,它们的内容就不应该被比较,而只考虑它们的签名 - 这是文档所说和我所需要的行为。 - martineau