在rails迭代CSV中,记录错误但不停止循环



我想遍历一个格式错误的CSV,如下所示:

"col1"、1000、"col2"、"格式错误"col3、"col4">

"col1"、1000、"col2"、"col3"、"col4">

"col1"、1000、"col2"、"格式错误的col3"、"col4">

使用Rails,因此,当在一行中发现错误时,会抛出CSV::MalformedCSVError,但循环不会停止。

我寻找了不同的解决方案,但直到知道都没有成功(

目前我有一个这样的方法:

def iterate_csv
puts 'lets iterate!!'
CSV.foreach(@file) { |line| 
begin
puts 'loop is on fire...'
# handle line here
rescue CSV::MalformedCSVError => e
puts e
# handle malformed row here...
next
end
}
end

我在谷歌上找到的所有帮助都无济于事。。感谢您的任何意见!

如果你想停止循环,你应该放break而不是next

相关内容

最新更新