Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append data to csv file

I want to append data to csv file. I get that data from user using html form. My current code adds data to csv file but it does not append. So when user enters their detail hit register button then it erase the previously added data the insert the new one in that place. So how can I append new data so that it saves in the next row and keeps the rest of the data in place?

Here is what I am doing.

full_name = params["full_name"]
email = params["email"]
phone = params["phone"]
organization = params["organization"]
job = params["job"]
diet = params["diet"]
address = params["address"]
code = params["code"]
city = params["city"]
cost_pool = params["cost_pool"]

CSV.open("participants_info.csv", "wb") do |csv|
  csv << [full_name, email, phone, organization, job, diet, address, code, city, cost_pool]
end
like image 798
Om3ga Avatar asked Jul 11 '12 06:07

Om3ga


3 Answers

``a'' Write-only, starts at end of file if file exists, otherwise creates a new file for writing.

``a+'' Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing

use CSV.open("participants_info.csv", "a+")

like image 96
Sully Avatar answered Nov 01 '22 07:11

Sully


Open file in append mode (ab)

CSV.open("participants_info.csv", "ab") do |csv|
#...
end
like image 25
Pritesh Jain Avatar answered Nov 01 '22 09:11

Pritesh Jain


File.open('filename', 'a'){ |outfile|
  CSV::Writer.generate(outfile) do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']
  end
}
like image 32
rafamart Avatar answered Nov 01 '22 08:11

rafamart