![](/img/trans.png)
[英]CSV::MalformedCSVError: New line must be <“\n\r”>
[英]Rescue CSV::MalformedCsvError: Illegal quoting in line n
在尝试解析数组,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 x行中的非法引用 (即“只是自己阅读文件” - 我想我在下面尝试过)。
这个SO Q&A( 我怎样才能进一步处理导致Ruby FasterCSV库抛出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中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.