Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a column to a CSV file?

Tags:

ruby

csv

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
like image 289
sherbert Avatar asked Sep 03 '15 15:09

sherbert


3 Answers

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
like image 159
steenslag Avatar answered Nov 16 '22 21:11

steenslag


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.

like image 2
Sculper Avatar answered Nov 16 '22 20:11

Sculper


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
like image 1
Subhash Rajagopal Avatar answered Nov 16 '22 22:11

Subhash Rajagopal