I have the following CSV file:
header 1, header 2, header 3
summin 1, summin 2, summin 3
summin 4, summin 5, summin 6
How would I append a column of data using the CSV class, so the result would look something like:
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
When a CSV-file has headers then you can access and manipulate columns:
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
The only method I could come up with that uses the CSV class is to read the file, then rewrite the data with the extra column. Let's generate your CSV data:
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
We could iterate over this with CSV.parse
(though you may wish to use CSV.foreach
if you're reading from a file), and create the new CSV data within the block:
# 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
The resulting output of the above is your final 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
Note that when writing to a file, you'll want to use CSV.open
, rather than CSV.generate
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With