gpt4 book ai didi

Python 3. 需要写入文件,检查是否存在一行,然后重新写入文件

转载 作者:太空狗 更新时间:2023-10-29 22:30:52 25 4
gpt4 key购买 nike

我最近从一个 friend 的死硬盘中恢复了大量照片,我决定用 python 编写一个程序来:

遍历所有文件

检查他们的MD5Sum

检查文本文件中是否存在MD5Sum

如果是,请用“已找到重复项”告诉我

如果不是,则将 MD5Sum 添加到文本文件中。

最终目标是删除所有重复项。但是,当我运行这段代码时,我得到以下信息:

Traceback (most recent call last):
File "C:\Users\godofgrunts\Documents\hasher.py", line 16, in <module>
for line in myfile:
io.UnsupportedOperation: not readable

我这样做是完全错误还是我只是误会了什么?

import hashlib
import os
import re

rootDir = 'H:\\recovered'
hasher = hashlib.md5()


with open('md5sums.txt', 'w') as myfile:
for dirName, subdirList, fileList in os.walk(rootDir):
for fname in fileList:
with open((os.path.join(dirName, fname)), 'rb') as pic:
buf = pic.read()
hasher.update(buf)
md5 = str(hasher.hexdigest())
for line in myfile:
if re.search("\b{0}\b".format(md5),line):
print("DUPLICATE HAS BEEN FOUND")
else:
myfile.write(md5 +'\n')

最佳答案

您已在 with 语句中以写入模式 ('w') 打开文件。要同时打开它的写作和阅读模式,请执行以下操作:

with open('md5sums.txt', 'w+') as myfile:

关于Python 3. 需要写入文件,检查是否存在一行,然后重新写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017724/

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