formatting file

Steven Bethard steven.bethard at gmail.com
Wed Apr 6 11:07:02 EDT 2005


SPJ wrote:
> Hi,
> 
> I am new to python hence posing this question.
> I have a file with the following format:
> 
> test1    1.1-1   installed
> test1    1.1-1   update
> test2    2.1-1   installed
> test2    2.1-2   update
> 
> I want the file to be formatted in the following way:
> 
> test1    1.1-1   1.1-2
> test2    2.1-1   2.1-2
> 
> How can I achieve this? I am stuck here.

py> import itertools as it
py> for line1, line2 in it.izip(f, f):
...     line1, line2 = [line.split() for line in [line1, line2]]
...     print '\t'.join(line1[:2] + line2[1:2])
...
test1	1.1-1	1.1-2
test2	2.1-1	2.1-2

where f is the file containing your data.  I assumed it looked like:

py> import StringIO as strio
py> f = strio.StringIO("""\
... test1    1.1-1   installed
... test1    1.1-2   update
... test2    2.1-1   installed
... test2    2.1-2   update
... """)

STeVe



More information about the Python-list mailing list