ruby-on-rails - 救援 CSV::MalformedCsvError:第 n 行非法引用

标签 ruby-on-rails csv error-handling

在尝试解析数组、AR 模型导入等时,CSV 文件有问题似乎是一个常见问题。除了在 MS Excel 中打开并另存为 之外,我还没有找到有效的解决方案> 每天(还不够好!)。

在一个 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

最佳答案

您的解决方案有效。预期结果驻留在变量 my_array 中。

关于ruby-on-rails - 救援 CSV::MalformedCsvError:第 n 行非法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37277866/

相关文章:

PHP 正则表达式和 CSV 验证

php - 导出大型 CSV 文件

sql-server - 如何处理来自SQL Server用户的错误?

r - 密度错误。默认: x must be numeric

error-handling - Golang 组合错误

ruby-on-rails - 错误处理多模型表格

ruby-on-rails - 在 Rspec 中添加 Controller 宏

ios - 如何获取iOS项目中项目文件的路径?

ruby-on-rails - 如何解析服务器端(rails)中的复选框值?

ruby-on-rails - Neo4j rb 查找 2 个节点之间的连接