Using StopIteration
Peter Otten
__peter__ at web.de
Mon May 8 14:46:03 EDT 2006
tkpmep at hotmail.com 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:
ProcessLine(line)
break
f.close()
A for instead of the inner while loop makes the f.next() 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 = f.next()
> except StopIteration:
break
else:
# only if StopIteration was not triggered
# and thus break not reached
ProcessLine(line)
f.close()
> 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?
By breaking out of the while loop as shown above.
(all changes untested)
Peter
More information about the Python-list
mailing list