question re file as sequence

Matteo Dell'Amico della at toglimi.linux.it
Sun Jul 11 03:39:02 EDT 2004


Christopher T King wrote:
> Sticking with readline will probably be easiest:
> 
> f = open(filename)
> for line in iter(f.readline,''):
>    if line == 'Fruit:\n':
>       print f.readline()

The (almost identical) solution using iterators is:

f = open(filename)
for line in f:
     if line == 'Fruit:\n':
         print f.next()

Of course, in this case you have to make sure a new line exists, or 
handle the corresponding StopIteration exception.

-- 
Ciao,
Matteo



More information about the Python-list mailing list