按列对csv文件进行排序

时间:2015-09-27 06:00:13

标签: python file sorting csv

我想根据第一列中的内容按字母顺序对csv文件中的数据进行排序。例如,如果文件包含:

city/month,Jan,Feb,Mar,Apr

Melbourne,41.2,35.5,37.4,29.3

Brisbane,31.3,40.2,37.9,29

Darwin,34,34,33.2,34.5

它将被排序为:

city/month,Jan,Feb,Mar,Apr

Brisbane,31.3,40.2,37.9,29

Darwin,34,34,33.2,34.5

Melbourne,41.2,35.5,37.4,29.3

到目前为止我做了什么,正确排序但它没有正确地返回答案,而不是以表格格式返回它,它将所有内容作为列表返回 - 任何想法为什么会这样?

import csv
import operator

def sort_records(csv_filename, new_filename):

  f = open(csv_filename)

  csv1 = csv.reader(f, delimiter = ',')

  new_filename = sorted(csv1)

  return new_filename

  f.close()

1 个答案:

答案 0 :(得分:3)

>>> import csv
>>> import operator

>>> def sort_records(csv_filename, new_filename):
...     with open(csv_filename, 'r') as i, open(new_filename, 'w') as o:
...         reader = csv.reader(i, delimiter = ',')
...         writer = csv.writer(o, delimiter=',')
...         writer.writerow(next(reader)) # header row
...         writer.writerows(sorted(reader, key=operator.itemgetter(0)))

>>> sort_records('a.csv', 'b.csv')