在Python中,是否有比较两个文本文件内容是否相同的简明方法?

我不在乎分歧是什么。 我只想知道内容是否有所不同。

低级方式:

from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... 

高层次的方式:

 import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ... 

如果您要提高基本效率,您可能首先需要检查文件大小:

 if os.path.getsize(filename1) == os.path.getsize(filename2): if open('filename1','r').read() == open('filename2','r').read(): # Files are the same. 

这样可以节省您阅读两个文件的每一行,甚至不是相同的大小,因此不能相同。

(甚至比这更进一步,你可以调用每个文件的快速MD5sum并比较这些文件,但是这不是“Python中”,所以我会在这里停止)。

这是一个function样式的文件比较function。 如果文件大小不同,则立即返回False; 否则,它将以4KiB块大小读取,并在第一次差异时立即返回False:

 from __future__ import with_statement import os import itertools, functools, operator def filecmp(filename1, filename2): "Do the two files have exactly the same contents?" with open(filename1, "rb") as fp1, open(filename2, "rb") as fp2: if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size: return False # different sizes ∴ not equal fp1_reader= functools.partial(fp1.read, 4096) fp2_reader= functools.partial(fp2.read, 4096) cmp_pairs= itertools.izip(iter(fp1_reader, ''), iter(fp2_reader, '')) inequalities= itertools.starmap(operator.ne, cmp_pairs) return not any(inequalities) if __name__ == "__main__": import sys print filecmp(sys.argv[1], sys.argv[2]) 

只是一个不同的:)

由于我不能评论别人的答案,我会写我自己的。

如果你使用md5,你绝对不能只使用md5.update(f.read()),因为你会使用太多的内存。

 def get_file_md5(f, chunk_size=8192): h = hashlib.md5() while True: chunk = f.read(chunk_size) if not chunk: break h.update(chunk) return h.hexdigest() 
f = open(filename1, "r").read() f2 = open(filename2,"r").read() print f == f2
f = open(filename1, "r").read() f2 = open(filename2,"r").read() print f == f2 

对于较大的文件,您可以计算文件的MD5或SHA散列。

我将使用MD5的文件内容的散列。

 import hashlib def checksum(f): md5 = hashlib.md5() md5.update(open(f).read()) return md5.hexdigest() def is_contents_same(f1, f2): return checksum(f1) == checksum(f2) if not is_contents_same('foo.txt', 'bar.txt'): print 'The contents are not the same!' 
 from __future__ import with_statement filename1 = "G:\\test1.TXT" filename2 = "G:\\test2.TXT" with open(filename1) as f1: with open(filename2) as f2: file1list = f1.read().splitlines() file2list = f2.read().splitlines() list1length = len(file1list) list2length = len(file2list) if list1length == list2length: for index in range(len(file1list)): if file1list[index] == file2list[index]: print file1list[index] + "==" + file2list[index] else: print file1list[index] + "!=" + file2list[index]+" Not-Equel" else: print "difference inthe size of the file and number of lines"