Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use operator.itemgetter() to sort csv files

Tags:

python

csv

I have a set of values in a csv file. The values are shown below.I want those values to be sorted by a layer column, that has values 7208 and 7209 in the example below. Otherwise I want the csv file to be exactly as it is. My code below doesn't seem to sort it correctly.

Here's the csv file:

l_d,l_t,utc,SI,UTC,La,Lon,H,layer,N,Pr,EId,Pype,BS,Vo,Te,Chs,PT,Pass
01-08,11:00:19,03:00:19,0x037,01-08_02:58:03,None,None,None,7208,None,None,None,None,87,15.4,None,None,None,MENT 
01-08,11:00:19,03:00:19,0x037,01-08_02:58:03,None,None,None,7209,None,None,None,None,87,15.4,None,None,None,MENT 

Here's my current code:

import sys
import csv
import operator

reader = csv.reader(open("M_B.csv"), delimiter=",")

sortedlist = sorted(reader, key=operator.itemgetter(9), reverse=True)

print(sortedlist)

with open("M_B_Sorted.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(sortedlist)
like image 894
liv2hak Avatar asked Nov 26 '25 21:11

liv2hak


1 Answers

First, the index is wrong. It should be 8.

And you need to convert the string to int; cannot be done solely with itemgetter:

sortedlist = sorted(reader, key=lambda row: int(row[8]), reverse=True)

In addition to that, you need to exclude header.

import csv

with open("M_B.csv") as fin, open("M_B_Sorted.csv", "wb") as f:
    reader = csv.reader(fin, delimiter=",")
    writer = csv.writer(f)
    header = next(reader)  # <--- Pop header out
    writer.writerow(header) # <--- Write header
    sortedlist = sorted(reader, key=lambda row: int(row[8]), reverse=True)
    writer.writerows(sortedlist)
like image 173
falsetru Avatar answered Nov 29 '25 10:11

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!