2013-09-26 48 views
5

我最近從朋友的死硬盤恢復了一噸圖片,並決定想用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') 
+0

關於你的縮進四個空格最好8將是更容易爲我們所有閱讀爲好。參見[PEP8](http://www.python.org/dev/peps/pep-0008/#indentation)。 – RyPeck

回答

3

已打開以書面方式('w')文件在你with聲明。要打開寫入和讀取模式,請執行以下操作:

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

所以我嘗試了,它仍然沒有寫。我在代碼中添加了一些打印語句,它沿着聲明md5 = str(hasher.hexdigest())的部分向下,並再次啓動os.walk for循環。 – godofgrunts

+0

@godofgrunts仔細檢查您的縮進。它可能會做你不想做的事情 – TerryA

+0

我不會說我100%確定我的縮進是正確的,但我很確定它是。 – godofgrunts