Python 3.需要写入文件,检查是否存在行,然后再次写入文件

god*_*nts 6 python io python-3.x

我最近从朋友的死硬盘中找到了一大堆照片,我决定想用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
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)

Ter*_*ryA 4

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

with open('md5sums.txt', 'w+') as myfile:
Run Code Online (Sandbox Code Playgroud)