6.8.2 比较文件
cmp()用于比较文件系统上的两个文件。
import filecmp
print('common_file :',end=' ')
print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file'),
end=' ')
print(filecmp.cmp('example/dir1/common_file',
'example/dir2/common_file',
shallow=False))
print('not_the_same:',end=' ')
print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same'),
end=' ')
print(filecmp.cmp('example/dir1/not_the_same',
'example/dir2/not_the_same',
shallow=False))
print('identical :',end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir2/file_only_in_dir2'),
end=' ')
print(filecmp.cmp('example/dir1/file_only_in_dir1',
'example/dir2/file_only_in_dir2',
shallow=False))
shallow参数告诉cmp()除了文件的元数据外,是否还要查看文件的内容。默认情况下,会使用由os.stat()得到的信息来完成一个浅比较。如果结果是一样的,则认为文件相同。因此,对于同时创建的相同大小的文件,即使它们的内容不同,也会报告为是相同的文件。当shallow为False时,则要比较文件的内容。
运行结果:
如果非要递归比较两个目录中的一组文件,则可以使用cmpfiles()。参数是目录名和两个位置上要检查的文件列表。传入的公共文件列表应当只包含文件名(目录会导致匹配不成功),而且这些文件在两个位置上都应当出现。下一个例子显示了构造公共列表的一种简单方法。与cmp()一样,这个比较也有一个shallow标志。
import filecmp
import os
# Determine the items that exist in both directories.
d1_contents = set(os.listdir('example/dir1'))
d2_contents = set(os.listdir('example/dir2'))
common = list(d1_contents & d2_contents)
common_files = [
f
for f in common
if os.path.isfile(os.path.join('example/dir1',f))
]
print('Common files:',common_files)
# Compare the directories.
match,mismatch,errors = filecmp.cmpfiles(
'example/dir1',
'example/dir2',
common_files,
)
print('Match :',match)
print('Mismatch :',mismatch)
print('Errors :',errors)
cmpfiles()返回3个文件名列表,分别包含匹配的文件、不匹配的文件和不能比较的文件(由于权限问题或出于其他原因)。
运行结果: