formatting file
Peter Otten
__peter__ at web.de
Wed Apr 6 14:06:16 EDT 2005
SPJ wrote:
> 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
The following program expects a sorted input file:
import itertools
from operator import itemgetter
def pivot(infile, outfile,
getkey=itemgetter(0), getvalue=itemgetter(1), sep="\t"):
if not hasattr(infile, "read"):
infile = file(infile)
if not hasattr(outfile, "write"):
outfile = file(outfile, "w")
records = (line.split() for line in infile)
for key, items in itertools.groupby(records, getkey):
out_record = [key]
out_record.extend(getvalue(item) for item in items)
print >> outfile, sep.join(out_record)
if __name__ == "__main__":
import sys
infile, outfile = sys.argv[1:]
if infile == "-": infile = sys.stdin
if outfile == "-": outfile = sys.stdout
pivot(infile, outfile)
More information about the Python-list
mailing list