如何进一步处理导致Ruby FasterCSV库抛出MalformedCSVError的数据行?

s01*_*ist 4 ruby fastercsv

传入的数据文件包含格式错误的CSV数据(如非转义引号)以及(有效)CSV数据(如包含新行的字段).如果检测到CSV格式错误,我想对该数据使用替代例程.

使用以下示例代码(简称为简称)

FasterCSV.open( file ){|csv|
  row = true
  while row
    begin
      row = csv.shift
      break unless row
      # Do things with the good rows here...

    rescue FasterCSV::MalformedCSVError => e
      # Do things with the bad rows here...
      next
    end
  end
}
Run Code Online (Sandbox Code Playgroud)

MalformedCSVError是在csv.shift方法中引起的.如何从rescue子句中访问导致错误的数据?

ste*_*lag 8

require 'csv' #CSV in ruby 1.9.2 is identical to FasterCSV

# File.open('test.txt','r').each do |line|
DATA.each do |line|
  begin
    CSV.parse(line) do |row|
      p row #handle row
    end
  rescue  CSV::MalformedCSVError => er
    puts er.message
    puts "This one: #{line}"
    # and continue
  end
end

# Output:

# Unclosed quoted field on line 1.
# This one: 1,"aaa
# Illegal quoting on line 1.
# This one: aaa",valid
# Unclosed quoted field on line 1.
# This one: 2,"bbb
# ["bbb", "invalid"]
# ["3", "ccc", "valid"]   

__END__
1,"aaa
aaa",valid
2,"bbb
bbb,invalid
3,ccc,valid
Run Code Online (Sandbox Code Playgroud)

只需将文件逐行提供给FasterCSV并挽救错误.