我有一个很大的文件夹,里面有很多文件(.txt
文件)。我想检查某些文件是否有相同的内容。文件名都是唯一的。
我知道如何比较两个文件,如下所示:
>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False
但我想一次比较所有文件。有人知道我该怎么做吗?
这是一种通过MD5 sum对所有.txt文件进行分类的简单方法:
import glob
import hashlib
import json
from collections import defaultdict
def md5(filename):
hash_md5 = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
dct = defaultdict(list)
for filename in glob.iglob('**/*.txt', recursive=True):
dct[md5(filename)].append(filename)
因此,如果您只想检查哪些内容具有相同的内容,就可以像这样查询:
print([v for k, v in dct.items() if len(v) > 1])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句