Parsing CSV files with escaped newlines in Ruby?

How to handle CSV files with escaped newlines in Ruby? I do not see anything obvious in CSV or FasterCSV.

Here is an example input:

"foo", "bar"
"rah", "baz \
and stuff"
"green", "red"

In Python, I would do the following:

csvFile = "foo.csv"
csv.register_dialect('blah', escapechar='\\')
csvReader = csv.reader(open(csvFile), "blah")
+3
source share
2 answers

If the fields containing the new line are correctly quoted (as in your example data), then the Ruby csv parser can handle them just fine. However, if you want Ruby to remove the escape character (as Python can do by installing it escapechar), I also don't see a method for doing this in Ruby docs. (By the way, with Ruby 1.9, FasterCSV is the default Ruby csv implementation.)

#!/usr/bin/env ruby -w
require 'csv'

CSV.foreach('test.csv') do |rec|
  puts "Record: #{rec}"
end

:

telemachus ~ $ ruby read.rb 
Record: ["foo", "bar"]
Record: ["rah", "baz \\\nand stuff"]
Record: ["green", "red"]
+7

Ruby, .

( ). Python , , .

, Perl- , Ruby, , Ruby . , () lookbehind, split() , , a.

:

$allLines=$wholeFile.split(/(?<!\\)\n/m);

Ruby , (? <! . , , - . , CSV, : http://snippets.aktagon.com/snippets/246-How-to-parse-CSV-data-with-Ruby

+1

Source: https://habr.com/ru/post/1712230/


All Articles