python - 读取一个 csv 文件,然后对其进行排序,然后对其进行重写
问题描述
我想读入一个 csv 文件,对其进行排序,然后重写一个新文件。有什么帮助吗?
解决方案
您可能应该看一下该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)
推荐阅读
- prolog - prolog 中的家庭关系:hasNoChild(X) 方法
- spring-boot - spring boot unix service is not pick up mode option
- php - WP_Query - 按另一种帖子类型的元类型排序帖子
- python - 迭代期间在同一行上打印 dict 的值和下一个值,项目数为奇数
- javascript - 运行代码,例如登录,取决于执行哪个测试套件
- oracle - 批处理文件 - 在 For 循环中调用动态 Oracle 查询
- regex - 使用 Grep 在匹配前获取捕获组和行
- drupal-7 - Drupal 7 utf8mb4 支持:“请转换表”警告...转换表后
- pdf - 将 jsPDF 合并到您现有的 Vuetify 项目中
- ios - 快速实例化 UIViewController