CSV - Unquoted fields do not allow \r or \n (line 2)

user984621 picture user984621 · Jul 18, 2012 · Viewed 33.1k times · Source

Trying to parse a CSV file, but still getting the error message Unquoted fields do not allow \r or \n (line 2)..

I found here at SO similar topic, where was a hint to do following:

  CSV.open('file.csv', :row_sep => "\r\n") do |csv|

but his unfortunately doesn't works me... I can't change the CSV file, so I would need to fix it in the code.

EDIT sample of CSV file:

A;B;C
1234;...

Is there any way to do it?

Many thanks!

Answer

jslivka picture jslivka · Jul 18, 2012

First of all, you should set you column delimiters to ';', since that is not the normal way CSV files are parsed. This worked for me:

CSV.open('file.csv', :row_sep => :auto, :col_sep => ";") do |csv|
    csv.each { |a,b,c| puts "#{a},#{b},#{c}" } 
end

From the 1.9.2 CSV documentation:

Auto-discovery reads ahead in the data looking for the next \r\n, \n, or \r sequence. A sequence will be selected even if it occurs in a quoted field, assuming that you would have the same line endings there.