[Tutor] Nested, line by line, file reading

Alan Gauld alan.gauld at btinternet.com
Sun Dec 16 16:38:28 CET 2007

"Alan Gauld" <alan.gauld at btinternet.com> wrote 

> found2 = False
> for line in file("prueba.txt"):
>     if '2' in line: found2 = True
>     if found2: print line
>     else: continue

Just after posting I realised it would be better to do:

found2 = False
for line in file("prueba.txt"):
    found2 = found2 or line.startswith('2')
    if found2: print line

The continue was superfluous and the if test 
less efficient that the boolean test.
line.startswith seems a more appropriate test too, 
and should be more efficient on long lines.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list