我最近從朋友的死硬盤恢復了一噸圖片,並決定想用python編寫一個程序於:Python 3.需要寫入一個文件,檢查是否存在一行,然後再次寫入文件
經過的所有文件
檢查他們的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')
關於你的縮進四個空格最好8將是更容易爲我們所有閱讀爲好。參見[PEP8](http://www.python.org/dev/peps/pep-0008/#indentation)。 – RyPeck