【问题标题】:Rescue CSV::MalformedCsvError: Illegal quoting in line n救援 CSV::MalformedCsvError:第 n 行中的非法引用
【发布时间】:2016-09-13 15:45:24
【问题描述】:

在尝试解析为数组、AR 模型导入等时出现错误的 CSV 文件似乎是一个常见问题。除了每天在 MS Excel 和 save as 中打开之外,我还没有找到可行的解决方案(不好足够的!)。

在一个外部提供的、每日更新的 60,000 行 csv 文件中,有一个错误:CSV::MalformedCSVError: Illegal quoting in line 95.(例如)。我很高兴跳过/忘记格式错误的行(即它只有 1/60000 的重要性)。

第一次尝试是使用CSV.foreach 或类似的,并且简单地使用begin rescue next end 来跳过错误。没有骰子。我希望这个 SO 接受的答案更详细一点:CSV.read Illegal quoting in line x(即“自己阅读文件”——我想我在下面尝试过)。

而且这个 SO Q&A (How can I further process the line of data that causes the Ruby FasterCSV library to throw a MalformedCSVError?) 似乎有希望,但接受的答案并没有......相当......在我看似相似的情况下工作(修改例如清晰度),通过 rake 任务执行:

file_path = "filename.csv"
my_array = []

File.open(file_path).each do |line| # `foreach` instead of `open..each` does the same
  begin     
    CSV.parse(line) do |row|
      my_array << row
    end
  rescue CSV::MalformedCSVError => er
    puts er.message
    counter += 1
    next
  end
  counter += 1
  puts "#{counter} read success"
end

输出 =>

1 read success
2 read success
...
94 read success
Illegal quoting in line 1 # strange that it says `line 1` vs `95`, which may be the crux of what I do not understand here (e.g. some kind of look ahead error)
96 read success
...
60000 read success 
  # I checked using `line.inspect`, and the 60000th row is indeed being read/inspected
rake aborted!

CSV:MalformedCSVError: Illegal quoting in line 95

【问题讨论】:

  • 采样线?如果有第 95 行和周围的行,那就太好了。
  • 我刚刚运行了您的代码,它会忽略格式错误的行并将其他所有内容推送到 my_array。这不是你想要的吗?
  • 拍摄,@littlecegian,我认为是因为我的终端抛出错误,数组不接受行(救援工作正常时我从未收到错误消息)!我刚刚运行了my_array.count,它有 59999 个字符串。
  • 太棒了!我只是把它作为答案然后

标签: ruby-on-rails csv error-handling


【解决方案1】:

您的解决方案有效。预期的结果位于变量 my_array 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    相关资源
    最近更新 更多