排序csv数据



任务是将csv文件排序并保存在新的csv文件中。使用下面的代码(下面的1(,当我打开新的csv文件时,我似乎得到了结果。然而,当我在家庭作业界面上运行代码时,它打印错误(下面2(。有人能确定为什么它不起作用吗?我也有这个问题的正确解决方案(下面3(。我不明白为什么我的不起作用。

Below1:

import csv
def sort_records(csv_filename, new_filename):
file = open(csv_filename)
lines = file.readlines()
newfile = open(new_filename, "w")
header = lines[0]
newfile.write(header)
lines.remove(header)
lines.sort(key=lambda x: x[0])
for item in lines:
newfile.write(item)
file.close()
newfile.close()

Below2:

城市/月份,1月,2月,3月,4月布里斯班,31.3,40.2,37.9,29达尔文,34,34,33.2,34.5墨尔本,41.2,35.5,37.4,29.3

Below3:

import csv
def sort_records(csv_filename, new_filename):
csv_file = open(csv_filename)
reader = csv.reader(csv_file)
header = next(reader)
data2d = list(reader)
data2d.sort()
csv_file.close()
new_file = open(new_filename, "w")
writer = csv.writer(new_file)
writer.writerow(header)
writer.writerows(data2d)
new_file.close()

原始csv文件:

城市/月份,1月、2月、3月、4月、5月、6月、7月、8月、9月、10月、11月、12月墨尔本,41.2,35.5,37.4,29.3,23.9,16.8,18.2,25.7,22.3,33.5,36.9,41.1布里斯班,31.3,40.2,37.9,29,30,27,26.7,28.8,31.2,34.1,31.1,31.2达尔文,34,34,33.2,34.5,34.8,33.9,32,34.3,36.1,35.4,37,35.5珀斯,41.9,41.542.4,36,26.9,24.5,23.8,24.3,27.6,30.7,39.8,44.2阿德莱德,42.1,38.1,39.7,33.5,26.3,16.5,21.4,30.4,30.2,34.9,37.1,42.2堪培拉,35.8,29.6,35.1,26.5,22.4,15.3,15.7,21.9,22.1,30.8,33.4,35霍巴特,35.5,34.1,30.7,26,20.9,17.5,21.7,20.9,24.2,30.1,33.4悉尼,30.6,29,35.1,27.1,28.6,20.7,23.4,27.7,28.6,34.8,26.4,30.2

在这种情况下不需要额外的模块。打开输入文件进行读取(只读(,打开输出文件进行写入。

写出从输入到输出的第一行(列描述(。然后对从readlines返回的列表进行排序,并写入输出。

像这样:

ORIGINAL = 'original.csv'
NEW = 'new.csv'
with open(ORIGINAL) as original, open(NEW, 'w') as new:
new.write(next(original))
new.writelines(sorted(original.readlines(), key=lambda x: x.split(',')[0]))

我已经在我的机器上运行了你的代码,它按照预期工作。在排序之前,可以从这个作业界面打印出CSV文件吗?

相关内容

  • 没有找到相关文章

最新更新