Using StopIteration

tkpmep at hotmail.com tkpmep at hotmail.com
Mon May 8 14:23:28 EDT 2006


I create list of files, open each file in turn, skip past all the blank
lines, and then process the first line that starts with a number (see
code below)

filenames=glob.glob("C:/*.txt")
for fn in filenames:
    f =file(fn)
    line = " "
    while line[0] not in digits:
        line = f.next()
    ProcessLine(line)

If a file has only blank lines, the while loop terminates with a
StopIteration. How can I just close this file andd skip to the next
file if a StopIteration is raised? I tried the following:

filenames=glob.glob("C:/*.txt")
for fn in filenames:
    f =file(fn)
    line = " "
    while line[0] not in digits:
        try:
            line = f.next()
        except StopIteration:
            f.close()
            continue

    ProcessLine(line)

but got only a ValueError: I/O operation on closed file   for   line =
f.next(). It appears that the continue is taking me back to the top of
the while loop. How can I get back to the top of the for loop?

Thanks in advance 

Thomas Philips




More information about the Python-list mailing list