Newbie: fastcsv: Read rows, print rows

Discussion in 'Ruby' started by drubdrub, Jun 29, 2007.

  1. drubdrub

    drubdrub Guest

    New to Ruby. It probably shows. Trying to accomplish some simple
    initial tasks, and study.

    1. Read rows from a CSV file
    2. Write rows to STDOUT

    A cat() equivalent.

    I've been looking but don't find it. Are there any good tutorials on
    using fastcsv? This might be a good candidate for such.

    Many thanks!

    'fastercsv'"rfile2", "r") do |csv|
    csvData.each{|row| puts "row: ${row}"}
    drubdrub, Jun 29, 2007
    1. Advertisements

  2. Welcome to Ruby!
    There's the documentation:

    You'll find basic reading and writing information on this page in

    There are also some examples in the source:
    The above should be on one line. You may also need to add a:

    require 'rubygems'

    before requiring FasterCSV, depending on your environment.
    There is an error is on the line above, which needs to be:
    Change csvData to csv in the line above. Also replace ${row} with #
    That should get you running.

    You can do this a little easier using foreach():

    FCSV.foreach("rfile2") do |row|
    p row

    Hope that helps.

    James Edward Gray II
    James Edward Gray II, Jun 29, 2007
    1. Advertisements

  3. drubdrub

    drubdrub Guest

    Thanks for such a rapid, patient response!

    You certainly helped me get "unstuck". Appreciate the references. I
    had found the doc pages but was still laboring.

    For the record, here is my working code. No rocket science, but may
    be useful to someone.

    All the best!

    require 'rubygems'
    require 'fastercsv'

    infile = "infile2.csv", "r") do |row|
    row.each{|row| puts "row: #{row.inspect}"}

    drubdrub, Jun 29, 2007
  4. Just be aware about the fact that row is changed after row.each
    Stefan Mahlitz, Jul 2, 2007
  5. drubdrub

    drub Guest

    Thanks for the warning!

    There must be a fastercsv feature to get rid of the encapsulating '
    characters (e.g. the single quote)., "r") do |row|

    row.each do |
    field.each do |field|
    print "|"
    print "#{field}"

    puts "|"

    The output:
    |'field 1'|'field 2'|'field 3'|

    I want:
    |field 1|field 2|field 3|
    drub, Jul 16, 2007
  6. The single quote character is not part of the CSV specification, so
    they are not removed. I'm afraid you will need to pluck those out by

    James Edward Gray II
    James Edward Gray II, Jul 17, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.