簡體   English   中英

整理csv條數據

[英]Sorting csv data

要求是將一個 csv 文件排序並保存在一個新的 csv 文件中。 使用下面的代碼(below1),當我打開新的 csv 文件時,我似乎得到了結果。 但是,當我在作業界面上運行代碼時,卻打印出了錯誤(下圖2)。 任何人都可以確定為什么它不起作用嗎? 我也有正確的解決方案(下圖 3)。 我不明白為什么我的不起作用。

下圖1:

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

下圖2:

城市/月,一月,二月,三月,四月 布里斯班,31.3,40.2,37.9,29 達爾文,34,34,33.2,34.5墨爾本,41.2,35.5,37.4,29.3

下圖 3:

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文件:

城市/月,一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月 墨爾本,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,26.7,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.5,42.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,15.1,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

我已經在我的機器上運行了您的代碼,它可以正常工作。 是否可以在排序前從這個作業界面打印出CSV文件?

在這種情況下不需要額外的模塊。 打開輸入文件進行讀取(只讀)和 output 文件進行寫入。

將輸入的第一行(列描述)寫入output。然后將readlines返回的列表排序並寫入output。

像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM