2013-02-11 156 views
0

我正在編寫一個程序來執行目錄中文件的文件完整性檢查。代碼中有3個嵌套循環。當我運行代碼時,前兩個循環很好,但第三個循環不會運行多次。Python嵌套循環失敗

import hashlib 
import logging as log 
import optparse 
import os 
import re 
import sys 
import glob 
import shutil 

def md5(fileName): 
    """Compute md5 hash of the specified file""" 
    try: 
     fileHandle = open(fileName, "rb") 
    except IOError: 
     return 
    m5Hash = hashlib.md5() 
    while True: 
     data = fileHandle.read(8192) 
     if not data: 
      break 
     m5Hash.update(data) 
    fileHandle.close() 
    return m5Hash.hexdigest() 

req = open("requested.txt") 
for reqline in req: 
    reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1] 
    reqDir = reqline[0:reqline.rfind('/') + 1] 
    ezfimlog = open("ezfimlog.txt", 'a') 
    actFile = open("activefile.txt") 
    tempFile = open("activetemp.txt", 'w') 
    for name in glob.glob(reqDir + reqName):  
     fileHash = md5(name) 

     actInt = 0 
     if fileHash != None: 
      print fileHash 
      for actLine in actFile: 
       actNameDir = actLine[0:actLine.rfind(' : ')] 
       actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1] 
       print (name + " " + actHash + " " + fileHash) 
       if actNameDir == name and actHash == fileHash: 
        tempFile.write(name + " : " + fileHash + "\n") 
        actInt = 1 
       if actNameDir == name and actHash != fileHash: 
        tempFile.write(name + " : " + actHash + "\n")   
        actInt = 1 
        ezfimlog.write("EzFIM Log: The file " + name + " was modified: " + actHash + "\n") 
      if actInt == 0: 
       ezfimlog.write("EzFIM Log: The file " + name + " was created: " + fileHash + "\n") 
       tempFile.write(name + " : " + fileHash + "\n")      
    shutil.copyfile("activetemp.txt", "activefile.txt") 
+0

比'actFile'包含至多一行。你有沒有調試* *? – StoryTeller 2013-02-11 18:10:58

回答

3

您打開一次actFile,然後嘗試多次讀取它。每次你想閱讀時都需要打開它。

移動這一行:

actFile = open("activefile.txt") 

,只是這一行之前:

 for actLine in actFile: 
+0

如果它是一個可管理的大小的文件,應該用'actFile.readlines()'將它讀入一個列表中,然後遍歷該列表而不是重讀該文件。 – BostonJohn 2013-02-11 18:51:16