如何在大型文件系统中查找重复文件同时避免内存

2024-04-28 11:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力避免重复我的mp3收藏(相当大)。我想通过检查文件内容来检查重复项,而不是查找相同的文件名。我已经写了下面的代码来做这个,但是大约一分钟后就会抛出一个MemoryError。有什么建议可以帮我解决这个问题吗?在

import os
import hashlib

walk = os.walk('H:\MUSIC NEXT GEN')

mySet = set()
dupe  = []

hasher = hashlib.md5()

for dirpath, subdirs, files in walk:
    for f in files:
        fileName =  os.path.join(dirpath, f)
        with open(fileName, 'rb') as mp3:
            buf = mp3.read()
            hasher.update(buf)
            hashKey = hasher.hexdigest()
            print hashKey
            if hashKey in mySet:
                dupe.append(fileName)
            else:
                mySet.add(hashKey)


print 'Dupes: ' + str(dupe)

Tags: inimportforosfilesfilenamemp3hashlib
2条回答

您可能有一个巨大的文件,无法像使用mp3.read()一次读取。改为读小部分。把它放到一个很好的小函数中也有助于保持主程序的整洁。下面是一个我自己使用了一段时间的函数(现在只是稍微打磨一下),它可能与您的类似:

import hashlib

def filehash(filename):
    with open(filename, mode='rb') as file:
        hasher = hashlib.md5()
        while True:
            buffer = file.read(1 << 20)
            if not buffer:
                return hasher.hexdigest()
            hasher.update(buffer)

更新:A^{}版本:

^{pr2}$

由于内存中已经缓存了一个1GB的文件并尝试了10次,这平均花费了5.35秒。read版本平均耗时6.07秒。在这两个版本中,Python进程在运行期间占用了大约10MB的RAM。在

我可能会坚持使用read版本,因为我更喜欢它的简单性,而且在我的实际用例中,数据还没有缓存在RAM中,我使用sha256(因此,总的时间会显著增加,readinto的小优势变得更加无关紧要)。在

hasher.update将内容附加到上一个。您可能需要为每个文件创建一个新的hasher

相关问题 更多 >