在尝试解析数组、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/