Import CSV file, trailing comma at end of row

I’m trying to import a CSV file, using the native CSV library. The
problem is, one of the rows has a comma at the end, due to the last
column in that row being blank. How can I get rid of the last comma in
the row and leave that column null?

Here’s what ive been trying:

CSV.open(“file.csv”).each do |row|
2.2.0 :142 > if row[-1]==’,’
2.2.0 :143?> row = row[0…-2]
2.2.0 :144?> end
2.2.0 :145?> puts row
2.2.0 :146?> end

and im still getting the
CSV::MalformedCSVError: Unquoted fields do not allow \r or \n

error.

How can I fix this? thanks

Happy Gilmore wrote in post #1171257:

I’m trying to import a CSV file, using the native CSV library. The
problem is, one of the rows has a comma at the end, due to the last
column in that row being blank. How can I get rid of the last comma in
the row and leave that column null?

Here’s what ive been trying:

CSV.open(“file.csv”).each do |row|
2.2.0 :142 > if row[-1]==’,’
2.2.0 :143?> row = row[0…-2]
2.2.0 :144?> end
2.2.0 :145?> puts row
2.2.0 :146?> end

and im still getting the
CSV::MalformedCSVError: Unquoted fields do not allow \r or \n

error.

How can I fix this? thanks

irb(main):001:0> str=“frank,dana,”
=> “frank,dana,”
irb(main):002:0> str.chop! if str[-1]==’,’
=> “frank,dana”

Try this in this line:

row = row[0…-2].chomp

Basically String#chomp removes /r/n at the end of the string. You need
to learn to do instrospection on objects, use inspect().