Modifying a textfile

Steven D'Aprano steve at
Thu Sep 3 13:52:44 CEST 2009

On Thu, 03 Sep 2009 03:21:25 -0700, Olli Virta wrote:

> What I need to do, is put the three rows that goes together and belong
> to
> certain subject, on a one line in the output textfile. And the next
> three
> rows again on a one new line. And that goes with the rest of the data to
> the end of the new file.
> Can't figure out a working loop structure to handle this.

The basic algorithm is:
- grab three lines from the input file
- write to the output file
- repeat until done

There are lots of ways to do this. Here's one:

# untested
out = file(outfile, 'w')
in_ = file(infile, 'r')
while True:
    # Grab three lines.
    a = in_.readline()
    if a == '':
        # Nothing more to read, we're done.
    b = in_.readline()
    c = in_.readline()
    out.write(a.rstrip() + ' ')
    out.write(b.rstrip() + ' ')
    out.write(c.rstrip() + '\n')

Here's another version:

# untested
out = file(outfile, 'w')
accumulator = []
for line in file(infile, 'r'):
    if len(accumulator) == 3:
        out.write("%s %s %s\n" % tuple(accumulator))
        accumulator = []
if accumulator:
    out.write("%s %s %s\n" % tuple(accumulator))

Chris has posted another method, using itertools. That's probably faster 
for very large files, but less readable. 


More information about the Python-list mailing list