[IronPython] Sorting CSV file

John Machin sjmachin at lexicon.net
Sat Jan 24 14:47:40 CET 2009

Sorry about the empty reply just then; finger trouble :-(

On 24/01/2009 5:13 PM, Sheetal Gophane wrote:
> Thank you all for your suggestions.
> I followed the following way
> 1.Define a class
> 2.In class overwrite __cmp__ function.
> 3.While reading file populate class object and append it in array.
> 4.Call array.sort() method. Internally it calls __cmp__ function.

That is rather a long cumbersome way around it. Why not use the 
facilities that are built into the sort method, like the cmp argument, 
or (better) the key argument?

See http://www.python.org/doc/2.4.2/lib/typesseq-mutable.html

Here's a demonstration; tested with IronPython 2.0 and Python 2.5

import StringIO

csv_data = """LogTime,ApetClientID,OperationName,Status,StartTime,Duration

def display(header, rows):
     print header
     for row in rows:
         print ','.join(row)

f = StringIO.StringIO(csv_data)
# f simulates a file object as returned by the open() builtin.
heading = f.next().rstrip()
data = [line.rstrip().split(',') for line in f]

# Sorting on the first column is boring -- it's already sorted.
# Let's sort on OperationName:
guff = data[:] # taking a copy
guff.sort(cmp=lambda x, y: cmp(x[2], y[2]))
print "OperationName -- cmp"
display(heading, guff)

# Better [read the manual to find out why]
guff = data[:] # taking a copy
guff.sort(key=lambda x: x[2])
print "OperationName -- key"
display(heading, guff)

# simulate SQL: ORDER BY OperationName, Duration DESC
guff = data[:] # taking a copy
guff.sort( key=lambda x: (x[2], -float(x[5])))
print "OperationName, Duration DESC -- key"
display(heading, guff)


More information about the Ironpython-users mailing list