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

CSV.open(name, "r").each do |row|
  puts row
end

      

And I am getting the following error:

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

      

The file name is a tab-delimited .txt file. I did it specifically. I have. CSV file, I went to excel and saved the file as a .txt tab. Thus, tabs are limited.

Can't CSV.open

read tab-delimited files?

+3


source to share


2 answers


Try specifying a field separator like this:

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

      



And memorize require 'csv'

and read the DOCS

+5


source


By default it CSV

uses a comma as a separator, this is because CSV stands for "comma separated values".

If you want a different separator (in this case, tabs), you need to make it explicit.

Example :



p CSV.new("aaa\tbbb\tccc\nddd\teee", col_sep: "\t").read

      

Relevant documentation: http://ruby-doc.org/stdlib-2.1.0/libdoc/csv/rdoc/CSV.html#new

0


source







All Articles