Ruby CSV: How can I read a tab-delimited file?

someone picture someone · Jul 24, 2015 · Viewed 8.3k times · Source
CSV.open(name, "r").each do |row|
  puts row
end

And I get the following error:

CSV::MalformedCSVError Unquoted fields do not allow \r or \n 

The name of the file is a .txt tab-delimited file. I made it specifically. I have a .csv file, I went to excel, and saved the file as .txt tab delimited. So it is tab delimited.

Shouldn't CSV.open be able to read tab-delimited files?

Answer

nextstep picture nextstep · Jul 24, 2015

Try specifying the field delimiter like this:

CSV.open("name", "r", { :col_sep => "\t" }).each do |row|
  puts row
end

And remember to require 'csv' and read the DOCS