按字母顺序排序csv文件

时间:2018-06-18 12:40:26

标签: python

我有这个csv文件:

ID,Name,Score1,Score2,Score3
100,Anne,3,4,5
101,Frank,1,2,3
102,Shawn,7,8,9
103,Bo,3,6,5
104,James,4,7,2

我想按名称按字母顺序对csv文件进行排序,如下所示:

ID,Name,Score1,Score2,Score3
100,Anne,3,4,5
103,Bo,3,6,5
101,Frank,1,2,3
104,James,4,7,2
102,Shawn,7,8,9

到目前为止,我已经尝试了这个:

def alphabetically_ordered(file_name):
Wanted_order = {"A":0,"B":1,"C":2,"D":3,"E": 4,"F":5,"G":6,"H":7,"I":8,"J": 9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T": 19,"U":20,"V":21,"W":22,"X":23,"Y": 24,"Z":25,"Æ":26,"Ø":27,"Å":28}
with open('file_name','rb') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)
    data = sorted(csv_input,key=lambda x: (Wanted_order[x[1]], socket.inet_aton(x[0])))
    return data

但是我收到了错误消息。

如何按名称的字母顺序对csv文件进行排序?

1 个答案:

答案 0 :(得分:4)

sorted中使用lambda key功能只能使用{/ p>}。

<强>实施例

import csv
with open(filename, "rU") as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)
    data = sorted(csv_input, key=lambda x: x[1])
    print(data)

<强>输出:

[['100', 'Anne', '3', '4', '5'], ['103', 'Bo', '3', '6', '5'], ['101', 'Frank', '1', '2', '3'], ['104', 'James', '4', '7', '2'], ['102', 'Shawn', '7', '8', '9']]

根据评论进行编辑

with open(filename, "wb") as f_input:
    csv_out = csv.writer(f_input)
    csv_out.writerow(header)
    csv_out.writerows(data)