readlines() a file in 2 parts.

Steve Holden sholden at holdenweb.com
Fri Feb 8 15:53:26 CET 2002


"Jason Price" <jprice at cosette.nampaz.com> wrote in message
news:87vgd85a7h.fsf 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.

    for line in file.readline():

will iterate over the characters contained in the next line from file. The
readline() method returns a string, being the next line from the file, and
the for statement loops over the components of that string as a sequence
(i.e. the characters).

>         What I tried to do origionally was:
>
> for line in file.readlines() :

The problem *here* is that the readlines() method reads the whole file in.
Since you haven't assigned that result to anything, you have no way of
retrieveing the back half of the file once you've identified where the front
half ends and executed the break.

>    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?
>
Punt! What you need is something like this:

    contents = file.readlines()

    for i in xrange(len(contents)):
        if contents[i] is the last line of the first part:
            break

    firstpart = contents[:i]
    secondpart = contents[i:]

regards
 Steve
--
Consulting, training, speaking: http://www.holdenweb.com/
Author, Python Web Programming: http://pydish.holdenweb.com/pwp/

"This is Python.  We don't care much about theory, except where it
intersects with useful practice."  Aahz Maruch on c.l.py







More information about the Python-list mailing list