在Python 2中,您应该导入itertools并使用其izip:
with open(file1) as f1:
with open(file2) as f2:
for line1, line2 in itertools.izip(f1, f2):
if line1 != line2:
print 'files are different'
break
使用内置zip
,两个文件将在循环开始时立即全部读入内存,这可能不是您想要的。在Python 3中,内置功能与Python 2中的功能zip
类似itertools.izip
-逐渐递增。