0

我正在编写一个程序来执行目录中文件的文件完整性检查。代码中有3个嵌套循环。当我运行代码时,前两个循环运行良好,但第三个循环运行不止一次。

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")
4

1 回答 1

3

您打开 actFile 一次,然后尝试多次读取它。每次要阅读时都需要打开它。

移动这一行:

actFile = open("activefile.txt")

就在这一行之前:

       for actLine in actFile:
于 2013-02-11T18:13:36.007 回答