比较 python 中两个文件的最佳方式,为什么?

Best way of comparing two files in python and why?

我有两个文件 a.txt 和 b.txt,所以我正在尝试使用如下所示的哈希进行比较。

#getting hash of files and comparing
file1 = hashlib.md5(open('a.txt', 'rb').read()).hexdigest()
file2 = hashlib.md5(open('b.txt', 'rb').read()).hexdigest() 
file1==file2--> returns True or False

这是一种方法,我们也可以使用如下的 filecmp

filecmp.cmp('a.txt','b.txt')--> returns True or False

这两种方式哪个更好,为什么?

filecmp.cmp('a.txt','b.txt', shallow=False) 正是您比较 2 个文件所需要的。

hashlib.md5() 会增加复杂性,更加 CPU 密集,需要更长的时间,最重要的是,当 2 个不同的文件具有相同的 md5 哈希值时,它会给出错误的结果。