读取一个csv文件,然后对其进行排序,然后将其重写

时间:2018-07-13 16:14:39

标签: python

我想读取一个csv文件,对其进行排序,然后重写一个新文件。有帮助吗?

1 个答案:

答案 0 :(得分:1)

您可能应该看看csv模块的python文档:

https://docs.python.org/3.6/library/csv.html

您也可以使用熊猫,但是如果您是python的新手,那可能会过大。

为您提供一些初始代码供您使用:

# file test.csv
2,a,x
0,b,y
1,c,z

代码:

import csv

csv_lines = []

# read csv
with open('test.csv') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        csv_lines.append(row)

# sort by first column
csv_lines_sorted = sorted(csv_lines, key=lambda x: x[0])

# write csv
with open('test_sorted.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    for row in csv_lines_sorted:
        writer.writerow(row)