The Accidental Rubyist

invalid byte sequence in UTF-8

CSV file reading in ruby 1.9 (fastercsv)

with one comment

Fastercsv, which is the default in ruby 1.9, uses a hash for specifying the column separator.
Here, we read a tab delimited file and push each row into an array. We also print the first 2 columns.


require ‘csv’

ctr = 0
@data = []
CSV.foreach(@file,:col_sep => “\t”) do |row|
@data << row
puts ” #{row[0]} | #{row[1]} ” #unless row[1] =~ /^\[x\]/
ctr += 1
end
puts ” #{ctr} rows “

To see the other options, do ri CSV::new in a Terminal. Some options are row_sep, field_size_limit, converters, headers (:first_row means the first row is treated as a header, if set to array then the array is used as a header), skip_blanks (true), force_quotes (true), write_headers (true), and a few others.


# git patching
URL
— Nick Quaranto

Dude, that’s nothing. I used to work across the hall from Linus Torvalds, and he used to pull down his pants and shake his balls at passers-by through his office window.
— barfolomew

Written by totalrecall

May 28, 2010 at 12:43 pm

Posted in ruby

One Response

Subscribe to comments with RSS.

  1. […] CSV file reading in ruby 1.9 (fastercsv) May 2010 […]


Leave a comment