Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

csv

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?

like image 359
someone Avatar asked Jul 24 '15 15:07

someone


2 Answers

By default CSV uses the comma as separator, this comes from the fact that 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

like image 149
Jesus Castello Avatar answered Oct 17 '22 20:10

Jesus Castello


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

like image 31
nextstep Avatar answered Oct 17 '22 21:10

nextstep