如何使用operator.itemgetter()对csv文件进行排序

时间:2015-11-17 06:40:21

标签: python csv

我在csv文件中有一组值。值如下所示。我希望这些值按层列排序,在下面的示例中具有值7208和7209。否则我希望csv文件完全一样。我的代码似乎没有正确排序。

这是csv文件:

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 

这是我目前的代码:

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)

1 个答案:

答案 0 :(得分:2)

首先,索引是错误的。它应该是8

您需要将字符串转换为int;不能单独使用itemgetter

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

除此之外,您还需要排除标题。

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)