Python如何按列id对csv文件进行排序

时间:2015-08-06 12:49:37

标签: python python-2.7

我有一个大型csv文件,格式为例如

POBOX,DEPT,ORGNAME,SUBBNAME,BUILDING,BNUM,STREET,LOCALITY,TOWN,COUNTY,POSTCODE,ID
,,,,,20,A STREET,,EXETER,DEVON,EX1 2SP,10013036001
,,,FLAT 0,,100,ALPHO ROAD,,EXETER,DEVON,EX2 8JD,10013036004
,,,JANB,,100,ALPHO ROAD,,EXETER,DEVON,EX2 8HZ,10013036003
,,,,,2A,BLACKHALL ROAD,,EXETER,DEVON,EX4 4HE,
,,,,,300,FOR STREET,HEAVITREE,EXETER,DEVON,EX1 2QN,

我已按Excel中的列ID(最后一列)手动对此文件进行排序并保存。 我想编写一个python方法来打开文件并按列id对其进行排序,然后将其写回文件,保存。 这可能吗?

里亚兹

1 个答案:

答案 0 :(得分:2)

import csv
array = csv.reader(open('1.csv','r'))
a = list(array)[:] # for a[0] - save first line
s_array = [a[0]] + sorted(a[1:], key=lambda x: x[-1])
csv.writer(open('2.csv', 'wb'), dialect='excel').writerows(s_array)

特别感谢:

Python tuples sorting based on last element

How to write a tuple of tuples to a CSV file using Python

Converting a csv file into a list of tuples with python