【问题标题】:Printing files that share the exact content打印共享确切内容的文件
【发布时间】:2018-03-29 19:16:46
【问题描述】:

我的目录有数百个文件,其中一些名称不同但内容重复。我已将文件分组到一个数组中并执行以下操作:

import os 
import itertools
import hashlib 
directory = os.listdir(input())
  for collection1, collection2 in itertools.combinations (directory, 2): 

    def check(data):
      data_check = hashlib.md5()
      data_check.update(open(data).read())
      return data_check.hexdigest()

    def match_check(c1, c2):
      return check(c1) == check(c2) 

match_check(collection1,collection2)

【问题讨论】:

  • 这里没有问题。在 SO 上,您不仅需要提供一个最小示例,还需要提供您所期望的与您的最小示例产生的结果之间的差异。
  • 好的。你有什么问题?
  • 我的示例不完整,我对代码的期望是打印具有完全相同内容的文件的匹配项。 t

标签: python itertools hashlib listdir


【解决方案1】:

您可以改为使用dict,使用MD5 作为键。例如:

files = {}

# In the loop:
  sum = hashlib.md5(open(data].read())
  if sum in files:
    # A file already exists for this MD5 sum, append the file
    files[sum].append(data)
  else:
    # First file with this MD5 sum
    files[sum] = [data]

然后您可以列出共享同一索引的dict 的值。例如:

for sum, l in files.values():
  if l.length() > 1:
    # More than one file with the same MD5 file
    # Do something

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2012-03-20
    相关资源
    最近更新 更多