Modifying a textfile

Chris Rebert clp2 at rebertia.com
Thu Sep 3 06:32:38 EDT 2009


On Thu, Sep 3, 2009 at 3:21 AM, Olli Virta<llvirta at gmail.com> wrote:
> Hi!
>
> So I got this big textfile. It's full of data from a database. About
> 150 or
> more rows or lines in a textfile.
> There's three first rows that belong to the same subject. And then
> next
> three rows belong to another subject and so on, to the end of the
> file.
>
> 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.

#completely untested
from itertools import  izip_longest
#from itertools recipes
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

output = file("output_file.whatever", 'w')
f = file("input_file.whatever", 'r')
for triple in grouper(3, f):
    triple = triple.replace('\n', '')
    output.write(triple)
    output.write('\n')

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list