Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: sort CSV file
|
Posted: Feb 9, 2004 5:53 PM
|
|
This would do it:
def SortCsvByField( filename, fieldNo, sep = ',' ): records = [line.split(sep) for line in file(filename)] records.sort( lambda a,b: cmp(a[fieldNo],b[fieldNo]) ) f = file(filename,'w') for rec in records: f.write( sep.join(rec) )
SortCsvByField( 'somefile.csv', 2, ',' )
...but this is Python code, not Java. So you could do one of the following things with it:
1) Download Python and use it.
2) Download Jython and use that.
3) Look at this as a pseudo code starting point and write the same thing in Java.
4) Wait for someone to write a Java answer.
(you might want to add a little error handling, as well -- in particular, you may want to filter out lines that don't match the cvs format, don't have enough fields, are emtpy, or what have you).
|
|