Question

I want to open a TSV (tab-separated-value) file, and save specific rows to a new CSV (comma-separated-value) file.

If the row contains 'NLD' in a field with the header 'Actor1Code', I want to save the row to a CSV; if not, I want to iterate to the next row. This is what I have so far, but apparently that is not enough:

require 'csv'

CSV.open("path/to.csv", "wb") do |csv| #csv to save to
  CSV.open('data.txt', 'r', '\t').each do |row| #csv to scrape
    if row['Actor1Code'] == 'NLD'
      csv << row
    else
    end
  end
end
Was it helpful?

Solution

Are you sure that you're calling CSV.open correctly? The documentation seems to suggest arguments are passed in as hashes:

CSV.open('data.txt', 'r', col_sep: "\t")

The error you're seeing is probably the result of '\t' being interpreted as a hash and referenced with [].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top