救援CSV :: MalformedCsvError:第n行中的引用非法 [英] Rescue CSV::MalformedCsvError: Illegal quoting in line n
问题描述
在尝试解析为数组,AR模型导入等时,似乎存在一个常见的问题,即CSV文件存在错误.除了在MS Excel中打开并另存为每天(不够好!).
Seems a common issue to have a buggy CSV file when attempting to parse to an array, AR model import, etc. I haven't found a working solution other than open in MS Excel and save as
every day (not good enough!).
在每天提供的60,000行外部提供的csv文件中,出现错误: CSV :: MalformedCSVError:第95行中的引用非法.
(例如).我很高兴跳过/忘记格式错误的行(即,它仅具有1/60000的重要性).
In a 60,000 row externally-provided, daily-updated csv file, there's an error: CSV::MalformedCSVError: Illegal quoting in line 95.
(as an example). I'm happy to skip/forget the malformed row (i.e. it has only 1/60000th importance).
首先尝试使用 CSV.foreach
或类似的方法,然后简单地开始
救援
下一个
结束
以跳过该错误.没有骰子.我希望这个已被接受的答案更加冗长: CSV.read在x行中非法引用()(即自己读取文件",我想我会在下面尝试).
First attempt is to use CSV.foreach
or similar, and simply begin
rescue
next
end
to skip the error. No dice. I wish this SO accepted answer was a wee bit more verbose: CSV.read Illegal quoting in line x (i.e. "just read the file yourself"--I think I tried that below).
And this SO Q&A (How can I further process the line of data that causes the Ruby FasterCSV library to throw a MalformedCSVError?) seems to have promise, but the accepted answer does not...quite...work in my seemingly similar case (modified for example clarity), executed via rake task:
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中.
Your solution works. The expected result resides in the variable my_array.
这篇关于救援CSV :: MalformedCsvError:第n行中的引用非法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!