Python 2 文档filecmp()
说:
除非给定了shallow并且是假的,否则具有相同
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文档已被改写,目前说如下,恕我直言,这是一种改进,只是因为它更好地暗示具有不同时间戳的文件即使在shallow
为 True 时仍可能被视为相等。
如果shallow为真,则具有相同
os.stat()
签名的文件被视为相等。否则,将比较文件的内容。
FWIW我认为简单地说这样的话会更好:
如果shallow
os.stat()
为真,则仅当 签名不相等时才比较文件内容 。