exception raised by nested iterator being ignored by for loop
Raymond Hettinger
python at rcn.com
Sat Nov 19 23:24:09 EST 2005
james t kirk wrote:
> 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.
Admiral Kirk,
The innermost for-loop is catching its own StopIteration. You need to
explicitly raise StopIteration in your next() method when there are no
more lines in the file (hint, add an else-clause to the for-loop).
Alternatively, you could simplify your life by writing the whole
wrapper as a generator:
import gzip
def wrapper(filename) :
if filename[-3:] == ".gz" :
fh = gzip.GzipFile(filename, "r")
else :
fh = open(filename, "r")
for line in fh:
if line[:1] != "t": # filter out lines starting with 't'
yield line.rstrip()
fh.close()
Raymond Hettinger
Starfleet Command
More information about the Python-list
mailing list