exception raised by nested iterator being ignored by for loop

james t kirk james.t.kirk at ussenterprise.com
Sat Nov 19 22:36:43 EST 2005


I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop. Wrapping the second for loop in a try/except clause
shows that the exception is being raised though. 

Could someone more familiar with the underlying implementation please
give me a hint as to why this is happening?


import gzip
class wrapper :
    
    def __init__ (self, filename) :
        if filename[-3:] == ".gz" :
            self.fh = gzip.GzipFile(filename, "r")
        else :
            self.fh = open(filename, "r")
        
    def __iter__ (self) :
        return self
    
    def next (self) :
        for line in self.fh :       # StopIteration raised here when
file exhausted
            if line[:1] == "t" :    # filter out lines starting with
't'
                continue
            return line.rstrip()

if __name__ == "__main__" :
    # using the file handle
    fh = open("test.txt")
    for line in fh :
        print line.rstrip()
    fh.close()
    
    # using the wrapper class
    fh = wrapper("test.txt")
    for line in fh :                # StopIteration ignored here
        print line




More information about the Python-list mailing list