首页 > 解决方案 > 对 CSV 文件进行排序并将结果保存为 CSV

问题描述

我想获取一个 csv 文件,对其进行排序,然后将其保存为 csv。这是我到目前为止所拥有的,无法弄清楚如何将其写入 csv 文件

import csv
with open('test.csv','r') as f:
    sample = csv.reader(f)
    sort = sorted(sample)

for eachline in sort:
     print (eachline)

标签: pythoncsv

解决方案


像这样简单的事情不需要熊猫:

# Read the input file and sort it
with open('input.csv') as f:
    data = sorted(csv.reader(f))
# write to the output file
with open('output.csv', 'w', newline='\n') as f:
    csv.writer(f).writerows(data)

python中的元组按字典顺序排序,这意味着它们按第一个值排序,如果它们相等,则按第二个值排序。您可以提供一个key函数来排序以按特定值排序。


推荐阅读