如何将列添加到CSV文件?

时间:2015-09-03 15:34:10

标签: ruby csv

我有以下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

3 个答案:

答案 0 :(得分:7)

当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

答案 1 :(得分:2)

我能想出的唯一使用CSV类的方法是读取文件,然后用额外的列重写数据。让我们生成您的CSV数据:

csv = CSV.generate do |csv|
    csv << ['header 1', 'header 2', 'header 3']
    csv << ['summin 1', 'summin 2', 'summin 3']
    csv << ['summin 4', 'summin 5', 'summin 6']
end

我们可以使用CSV.parse对此进行迭代(如果您正在读取文件,则可能希望使用CSV.foreach),并在块中创建新的CSV数据:

# Values for new column (including header)
new_values = ['header 4', 'new value 1', 'new value 2']

i = 0
CSV.parse(csv) do |row| 

    new_csv = CSV.generate do |new_csv| 
        new_csv << row + [new_values[i]]
        i += 1
    end 
    puts new_csv
end 

以上结果是最终的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.open,而不是CSV.generate

答案 2 :(得分:0)

require "csv"

column_to_add=["new value 1","new value 1"] 

CSV.open(/Folder/new_file_name.csv, "wb") do |csv|
  csv << ["header 1", "header 2", "header 3", "header 4"]
    CSV.foreach(/Folder/OriginalFile.csv, headers: true) do |row,index|
        csv << [row[1], row[2] , row[3] , column_to_add[index]]
    end
end