Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a copy of some columns of a CSV file in Ruby with different data in one column?

Tags:

ruby

csv

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

I will be using a subset of columns from "A.csv" and will have to update one column's values to new values in "B.csv". Ultimately, I will use this data from B.csv to validate against a database.

  1. How do I create a new CSV file?
  2. How do I copy the required columns' data from A.csv to "B.csv"?
  3. How do I append values for a particular column?

I am new to Ruby, but I am able to read CSV to get an array or hash.

like image 279
user1718712 Avatar asked Oct 04 '12 00:10

user1718712


People also ask

What does CSV parse Do Ruby?

The parser works in the Encoding of the IO or String object being read from or written to. Your data is never transcoded (unless you ask Ruby to transcode it for you) and will literally be parsed in the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the Encoding of your data.


1 Answers

As mikeb pointed out, there are the docs - http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html - Or you can follow along with the examples below (all are tested and working):

To create a new file:

In this file we'll have two rows, a header row and data row, 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 append data to a CSV

Almost the same formula as above only instead of using "wb" mode, we'll use "a+" mode. For more information on these see this stack overflow answer: What are the Ruby File.open modes and options?

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

Now when we open our file.csv we have:

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

Read from our CSV file

Now you know how to copy and to write to a file, to read a CSV and therefore grab the data for manipulation you just do:

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

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

like image 98
newUserNameHere Avatar answered Sep 22 '22 14:09

newUserNameHere