对 CSV 文件进行排序并将结果保存为 CSV

Cha*_*ier 0 python 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)
Run Code Online (Sandbox Code Playgroud)

mou*_*ail 6

你不需要 pandas 来做这样简单的事情:

# 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)
Run Code Online (Sandbox Code Playgroud)

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