readlines() a file in 2 parts.

Daniel Dittmar daniel.dittmar at sap.com
Fri Feb 8 10:07:53 EST 2002


> 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

import xreadlines

class TwoStepReadline:
    def __init__ (self, stream):
        self.iterator = xreadlines.xreadlines (stream)

    def __iter__ (self):
        return self

    def next (self):
        line = self.iterator.next ()
        if self.condition (line):
            self.next = self.iterator.next   # just a speed hack to remove
the test
            raise StopIteration
        else:
            return line

    def condition (self, line):
        must be implemented


iterator = TwoStepReadline (sys.stdin)
for line in iterator:
    process part 1

for line in iterator:
    process part2

You'll have to change this a bit depending on whether the triggering line
should be part of the first iteration, the second iteration or ignored
entirely (as in the implementation above).

Of course there are variations which might be more flexible:

iterator = xreadlines (sys.stdin)
for line in ReadUntil (iterator, re.compile ('some pattern')):
    process part 1

for line in iterator:
    process rermainder

Daniel






More information about the Python-list mailing list