Ruby unable to parse a CSV file: CSV::MalformedCSVError (Illegal quoting in line 1.) Ruby unable to parse a CSV file: CSV::MalformedCSVError (Illegal quoting in line 1.) ruby ruby

Ruby unable to parse a CSV file: CSV::MalformedCSVError (Illegal quoting in line 1.)


quote_chars = %w(" | ~ ^ & *)begin  @report = CSV.read(csv_file, headers: :first_row, quote_char: quote_chars.shift)rescue CSV::MalformedCSVError  quote_chars.empty? ? raise : retry end

it's not perfect but it works most of the time.

N.B. CSV.parse takes the same parameters as CSV.read, so either a file or data from memory can be used


Anand, thank you for the encoding suggestion. This solved the illegal quoting problem for me.

Note: If you want the iterator to skip over the header row add headers: :first_row, like so:

CSV.foreach("test.csv", encoding: "bom|utf-8", headers: :first_row)


I just had an issue like this and discovered that CSV does not like spaces between the col-sep and the quote character. Once I removed those everything went fine.So I had:

12,  "N",  12, "Pacific/Majuro"

but once I gsubed out the spaces using

.gsub(/,\s+\"/,',\"')

resulting in

12,"N",  12,"Pacific/Majuro"

everything went fine.