gpt4 book ai didi

python - 按列对 csv 文件进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:12 25 4
gpt4 key购买 nike

我想根据第一列的内容按字母顺序对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()

最佳答案

>>> 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')

关于python - 按列对 csv 文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com