重新排列 CSV,删除旧的并重新编写
Rearrange CSV, delete the old one and re-write
假设我有一个 CSV 文件
Name,Age
john,20
ana,30
steven,25
frank,27
如果我想根据 "age" 值按降序排列,得到这样的东西怎么办
Name,Age
ana,30
frank,27
steven,25
john,20
然后删除所有 CSV 行并根据新订单重写它们?
我知道从 CSV 创建散列并对其进行排序很热门,但不知道如何实现所描述的结果。
Ruby has a CSV library. You can use it to read, sort, and write your CSV files. The CSV
class is a wrapper around CSV::Table
。 CSV::Table
处理数据本身,而 CSV
主要提供从文件读取的能力。
require 'csv'
orig_table = CSV.table("test.csv");
orig_table
是一个 CSV::Table
对象。不幸的是,您不能直接就地对其行进行排序,但您可以将它们排序为 CSV::Row
对象的数组并将其放入新的 CSV::Table
.
sorted_rows = orig_table.sort { |a,b| b[:age] <=> a[:age] }
sorted_table = CSV::Table.new(sorted_rows)
然后您可以使用 to_csv
从中获取 CSV 字符串并将其写回文件。
File.open("test.csv", "w").write(sorted_table.to_csv)
假设我有一个 CSV 文件
Name,Age
john,20
ana,30
steven,25
frank,27
如果我想根据 "age" 值按降序排列,得到这样的东西怎么办
Name,Age
ana,30
frank,27
steven,25
john,20
然后删除所有 CSV 行并根据新订单重写它们?
我知道从 CSV 创建散列并对其进行排序很热门,但不知道如何实现所描述的结果。
Ruby has a CSV library. You can use it to read, sort, and write your CSV files. The CSV
class is a wrapper around CSV::Table
。 CSV::Table
处理数据本身,而 CSV
主要提供从文件读取的能力。
require 'csv'
orig_table = CSV.table("test.csv");
orig_table
是一个 CSV::Table
对象。不幸的是,您不能直接就地对其行进行排序,但您可以将它们排序为 CSV::Row
对象的数组并将其放入新的 CSV::Table
.
sorted_rows = orig_table.sort { |a,b| b[:age] <=> a[:age] }
sorted_table = CSV::Table.new(sorted_rows)
然后您可以使用 to_csv
从中获取 CSV 字符串并将其写回文件。
File.open("test.csv", "w").write(sorted_table.to_csv)