sort by column a csv file case insensitive
Dave Angel
d at davea.name
Mon Apr 16 01:24:17 EDT 2012
On 04/16/2012 01:11 AM, Lee Chaplin wrote:
> Hi all,
>
> I am trying to sort, in place, by column, a csv file AND sort it case
> insensitive.
> I was trying something like this, with no success:
Could you perhaps qualify that "no success" bit? Do you mean it didn't
output a file, or that the file wasn't sorted right, or that the data
wasn't in the file at all, or that you got an exception, or that you got
a syntax error, or that your disk filled up, or what? Please paste the
results of running it, along with a brief description of why that was
not a success.
It might also be useful to state your working environment, like you're
running 32 bit CPython version 1.7 on Windows 2009, or whatever. in
this case, I don't think it matters, but somebody else may know differently.
> import csv
> import operator
>
> def sortcsvbyfield(csvfilename, columnnumber):
> with open(csvfilename, 'rb') as f:
> readit = csv.reader(f)
> thedata = list(readit)
>
> thedata = sorted(thedata, key = lambda x:
> (operator.itemgetter(columnnumber) ,x[0].lower())) #!!!
> with open(csvfilename, 'wb') as f:
> writeit = csv.writer(f)
> writeit.writerows(thedata)
>
> The line marked is the culprit.
> Any help is greatly appreciated.
>
> Thanks,
> Lee
--
DaveA
More information about the Python-list
mailing list