0

I am writing a program to perform file integrity checks of files in a directory. There are 3 nested loops in the code. When I run the code, the first two loops work great but the third loop does not run more than once.

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")
1
  • Than actFile contains at most a single line. Have you debugged it at all!? Commented Feb 11, 2013 at 18:10

1 Answer 1

3

You open actFile once and then try to read it many times. You'll need to open it each time you want to read it.

Move this line:

actFile = open("activefile.txt")

to just before this line:

       for actLine in actFile:
Sign up to request clarification or add additional context in comments.

1 Comment

If it's a manageable sized file, you should read it into a list with actFile.readlines() and then loop over that list rather than rereading the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.