首页 > 解决方案 > 读取一个 csv 文件,然后对其进行排序,然后对其进行重写

问题描述

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

标签: python

解决方案


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

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

您也可以使用 pandas,但如果您是 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)

推荐阅读