我有以下CSV文件:
header 1, header 2, header 3
summin 1, summin 2, summin 3
summin 4, summin 5, summin 6
我将如何使用CSV类附加一列数据,因此结果将类似于:
header 1, header 2, header 3, header 4
summin 1, summin 2, summin 3, new value 1
summin 4, summin 5, summin 6, new value 2
最佳答案
当CSV文件具有标题时,您可以访问和操作列:
require "csv"
table = CSV.read("test.csv", {headers: true, col_sep: ", "})
# change col 3 in one go, (or add a new one: table["header_4"] = ['summin 3','summin 6'] ):
table["header_3"] = ['summin 3','summin 6']
# Add another col, row by row:
table.each do |row|
row["header_4"] = rand(9)
end
# write to file
CSV.open("test2.csv", "w") do |f|
f << table.headers
table.each{|row| f << row}
end
关于ruby - 如何将列添加到CSV文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32379909/