我想读取一个csv文件,对其进行排序,然后重写一个新文件。有帮助吗?
答案 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)