readlines() a file in 2 parts.

Aldo Cortesi aldo at nullcube.com
Fri Feb 8 19:50:40 EST 2002


Thus spake Jason Price (jprice at cosette.nampaz.com):

> I have several files to read that logically break into 2
> parts.  It would be much cleaner to write 2 different 'for
> line in file.readline() :' loops, but the break point is
> different in each file, so I don't know the starting line.
> What I tried to do origionally was:
> 
> for line in file.readlines() :
>    if condition :
>       break
>    else:
>       do thing 1
> 
> for line in file.readlines()
>    do thing 2
> 

> I tried both readlines and xreadlines, and neither seem to
> do what I'd like.  Is there a way to do this cleanly, or
> should I punt, and just make the loop more complex?



Jason,

Every time you run file.readlines() a brand new list of
lines is created from the file. What you really want to do
is to create an iterator - an object you can loop over, and
which will keep your "place" in the file. This is excactly
what xreadlines() does.

The general syntax you give above is correct, with a small
modification:

itr = open("file").xreadlines()

for line in itr:
    if condition:
        break
    else:    
        print line

for line in itr:
    print line  

If you are using Python 2.2, it is probably in better taste
to replace the first line with:

itr = iter(open("file"))

For more info on iterators in Python 2.2, see this article
by David Mertz:

http://www-106.ibm.com/developerworks/linux/library/l-pycon?t=grl,l=252,p=iterators



Cheers,



Aldo



---
Aldo Cortesi
aldo at nullcube.com





More information about the Python-list mailing list