python - 对 CSV 文件进行排序并将结果保存为 CSV
问题描述
我想获取一个 csv 文件,对其进行排序,然后将其保存为 csv。这是我到目前为止所拥有的,无法弄清楚如何将其写入 csv 文件
import csv
with open('test.csv','r') as f:
sample = csv.reader(f)
sort = sorted(sample)
for eachline in sort:
print (eachline)
解决方案
像这样简单的事情不需要熊猫:
# Read the input file and sort it
with open('input.csv') as f:
data = sorted(csv.reader(f))
# write to the output file
with open('output.csv', 'w', newline='\n') as f:
csv.writer(f).writerows(data)
python中的元组按字典顺序排序,这意味着它们按第一个值排序,如果它们相等,则按第二个值排序。您可以提供一个key
函数来排序以按特定值排序。
推荐阅读
- java - 支持库的 FragmentManager 类型不兼容
- java - 将应用程序部署到 AWS Lambda 会引发 Postgres 驱动程序错误
- python - 如何访问 ImageField 对象并将其显示到模板
- asp.net - nullreferenceexception:对象引用未设置为数据库调用中的对象实例
- url - .then() 内的 React-Native firebase listAll() URL
- c# - 我得到(索引超出了数组的范围)错误
- r - 将 tibble 转换为 ts 对象
- r - R中有没有办法计算用Bray-Curtis相异矩阵生成的层次聚类的间隙统计量?
- python - 将 Null 项插入集合 Mongodb (Pymongo)
- javascript - PixiJS:如何使用它的 ResizePlugin