How to create a new CSV file in Ruby?

I have a CSV file called "A.csv". I need to create a new CSV file called "B.csv" with data from "A.csv".

I will use a subset of the columns from "A.csv" and you will have to update one column value to the new value in "B.csv". Then I use this data from B.csv to check in the database.

  • How to create a new CSV file?
  • How to copy required column data from A.csv to "B.csv"?
  • How to add values ​​for a specific column?

I can read CSV, get array or hash.

+54
ruby csv
04 Oct 2018-12-12T00:
source share
2 answers

As Mikeb noted, there are documents - http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html - Or you can follow the examples below (all are tested and working):

To create a new file:

In this file we will have two lines: a header line and a data line, a very simple CSV:

require "csv" CSV.open("file.csv", "wb") do |csv| csv << ["animal", "count", "price"] csv << ["fox", "1", "$90.00"] end 

result, a file called "file.csv" with the following:

 animal,count,price fox,1,$90.00 



How to add data to CSV

Almost the same forum as above, instead of using the "wb" mode, we will use the "+" mode. For more information about this, see Answer: What are the modes and parameters of Ruby File.open?

 CSV.open("file.csv", "a+") do |csv| csv << ["cow", "3","2500"] end 

Now, when we open the file.csv file, we have:

 animal,count,price fox,1,$90.00 cow,3,2500 



Read in our CSV file

Now you know how to copy and write to a file, read CSV and, therefore, capture data for manipulations that you just do:

 CSV.foreach("file.csv") do |row| puts row #first row would be ["animal", "count", "price"] - etc. end 

Of course, this looks like one of hundreds of different ways to pull information from a CSV using this gem. For more information, I suggest visiting the documents now that you have the primer: http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

+121
Oct 30 '13 at 22:24
source share

Have you seen the Ruby CSV class? It seems pretty comprehensive. Check it out here: http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

+3
04 Oct
source share



All Articles