2013-02-11 159 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