gpt4 book ai didi

python - Python处理文件时出现内存错误

转载 作者:太空狗 更新时间:2023-10-30 00:02:21 25 4
gpt4 key购买 nike

我有一个备份硬盘驱动器,我知道它周围散布着重复文件,我认为编写一个小 python 脚本来查找并删除它们将是一个有趣的项目。我编写了以下代码只是为了遍历驱动器并计算每个文件的 md5 总和并将其与我将称之为“第一次遇到”列表的内容进行比较。如果 md5 和尚不存在,则将其添加到列表中。如果总和已经存在,则删除当前文件。

import sys
import os
import hashlib

def checkFile(fileHashMap, file):
fReader = open(file)
fileData = fReader.read();
fReader.close()
fileHash = hashlib.md5(fileData).hexdigest()
del fileData

if fileHash in fileHashMap:
### Duplicate file.
fileHashMap[fileHash].append(file)
return True
else:
fileHashMap[fileHash] = [file]
return False


def main(argv):
fileHashMap = {}
fileCount = 0
for curDir, subDirs, files in os.walk(argv[1]):
print(curDir)
for file in files:
fileCount += 1
print("------------: " + str(fileCount))
print(curDir + file)
checkFile(fileHashMap, curDir + file)

if __name__ == "__main__":
main(sys.argv)

该脚本处理了大约 10Gb 的文件,然后在“fileData = fReader.read()”行抛出 MemoryError。我认为,由于我在计算 md5 和后关闭 fReader 并将文件数据标记为删除,所以我不会遇到这个问题。如何在不遇到此内存错误的情况下计算 md5 总和?

编辑:我被要求删除字典并查看内存使用情况以查看 hashlib 中是否存在泄漏。这是我运行的代码。

import sys
import os
import hashlib

def checkFile(file):
fReader = open(file)
fileData = fReader.read();
fReader.close()
fileHash = hashlib.md5(fileData).hexdigest()
del fileData

def main(argv):
for curDir, subDirs, files in os.walk(argv[1]):
print(curDir)
for file in files:
print("------: " + str(curDir + file))
checkFile(curDir + file)

if __name__ == "__main__":
main(sys.argv)

我仍然遇到内存崩溃问题。

最佳答案

您的问题在于读取整个文件,它们太大,您的系统无法将其全部加载到内存中,因此会引发错误。

正如您在官方 Python 文档中所见,MemoryError是:

Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.

为了您的目的,您可以使用hashlib.md5()

在这种情况下,您必须按顺序读取 4096 字节的 block 并将它们提供给 Md5 函数:

def md5(fname):
hash = hashlib.md5()
with open(fname) as f:
for chunk in iter(lambda: f.read(4096), ""):
hash.update(chunk)
return hash.hexdigest()

关于python - Python处理文件时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com