简体   繁体   中英

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM