按列对 csv 文件进行排序
Posted
技术标签:
【中文标题】按列对 csv 文件进行排序【英文标题】:Sorting a csv file by column 【发布时间】:2015-12-24 15:17:40 【问题描述】:我想根据第一列中的内容按字母顺序对 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()
【问题讨论】:
***.com/questions/2089036/sorting-csv-in-python的可能重复 【参考方案1】:>>> 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')
【讨论】:
我收到一个属性错误:'_csv.reader' 对象没有属性'next'以上是关于按列对 csv 文件进行排序的主要内容,如果未能解决你的问题,请参考以下文章