3

I am trying to parse uploaded CSV files. Here's the full error message:

[Worker(host:PC.local pid:69594)] Job ImportJob (id=4) FAILED (3 prior attempts) with CSV::MalformedCSVError: Unquoted fields do not allow \r or \n (line 1).

And the CSV files looks like this:

A1;A2;A3;A4;A5
B1;B2;B3;B4;B5
C1;C2;C3;C4;C5

And this is how I loop through the data in the CSV file:

data = SmarterCSV.process(
  file,
  {
    :col_sep => ';',
    :chunk_size => 100,
    :remove_empty_values => false,
    :remove_empty_hashes => false
  }
) do |d|

What's the problem here? I've tried to put the headline to the file, even tried to remove it (the version posted above), but in both cases I get the same error. How do I get rid of it?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user984621
  • 46,344
  • 73
  • 224
  • 412

2 Answers2

3

Assuming the CSV file was created on Windows, it's not surprising that the line endings are "\r\n". Try explicitly making that your row separator:

:row_sep => "\r"

Putting it all together:

data = SmarterCSV.process(file, 
  :col_sep => ';', 
  :row_sep => "\r", 
  :chunk_size => 100, 
  :remove_empty_values => false, 
  :remove_empty_hashes => false) do |d|
Isaac Betesh
  • 2,935
  • 28
  • 37
1

I encountered this exact problem but with the built-in CSV module.

I solved it by using the IO read mode as text: 'rt', not 'r':

require 'csv'

CSV.open(file_name, 'rt').each do |row|
  # blah, blah
end
Chris Reay
  • 21
  • 1