【问题标题】:How to check in python if all files in a folder have different content?如果文件夹中的所有文件都有不同的内容,如何签入python?
【发布时间】:2018-08-01 11:54:20
【问题描述】:

我有一个很大的文件夹,里面有很多文档 (.txtfiles)。我想检查某些文件是否有相同的内容。文件名都是唯一的。

我知道如何比较两个文件如下:

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

但我想一次比较所有文件。有人知道我该怎么做吗?

【问题讨论】:

  • 1) 计算所有文件的哈希或校验和。 2) 使用collections.Counter 计算出现次数。 3) 保留计数≥2的条目。

标签: python windows compare directory


【解决方案1】:

这是一个简单的方法,可以通过 MD5 和对所有 .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])

【讨论】:

    【解决方案2】:

    你不需要 python,只需运行:

    md5sum * | sort >filelist.txt
    

    然后看看连续文件的MD5和是否相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2012-04-28
      • 2022-01-23
      • 2022-09-27
      • 2021-02-07
      • 2012-02-22
      相关资源
      最近更新 更多