Using StopIteration

Peter Otten __peter__ at
Mon May 8 20:46:03 CEST 2006

tkpmep at wrote:

> 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 = open(fn)
      for line in f:
          if line[:1] in digits:

A for instead of the inner while loop makes the call implicit.

> 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 =
>         except StopIteration:
          # only if StopIteration was not triggered
          # and thus break not reached

> but got only a ValueError: I/O operation on closed file   for   line =
> 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?

By breaking out of the while loop as shown above.
(all changes untested)


More information about the Python-list mailing list