加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:59:28 所属栏目:百科 来源:网络整理
导读:传入的数据文件包含格式错误的CSV数据(如非转义引号)以及(有效)CSV数据(如包含新行的字段).如果检测到CSV格式错误,我想对该数据使用替代例程. 使用以下示例代码(简称为简称) FasterCSV.open( file ){|csv| row = true while row begin row = csv.shift break
传入的数据文件包含格式错误的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
}

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读