Python 读取csv文件,然后对其排序,然后重写
我想读入一个csv文件,对其排序,然后重写一个新文件。有什么帮助吗?您可能应该看看Python 读取csv文件,然后对其排序,然后重写,python,Python,我想读入一个csv文件,对其排序,然后重写一个新文件。有什么帮助吗?您可能应该看看csv模块的python文档: 您也可以使用pandas,但如果您是python新手,这可能会有点过头 要为您提供一些初始代码,请执行以下操作: 代码: 你尝试了什么?有一个csv模块用于读写 # file test.csv 2,a,x 0,b,y 1,c,z import csv csv_lines = [] # read csv with open('test.csv') as csvfile:
csv
模块的python文档:
您也可以使用pandas,但如果您是python新手,这可能会有点过头
要为您提供一些初始代码,请执行以下操作:
代码:
你尝试了什么?有一个csv模块用于读写
# 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)