在尝试解析数组、AR 模型导入等时,出现有问题的 CSV 文件似乎是一个常见问题。除了在 MS Excel 中打开之外,我还没有找到可行的解决方案save as
每天(还不够好!)。
在外部提供的 60,000 行、每日更新的 csv 文件中,存在错误:CSV::MalformedCSVError: Illegal quoting in line 95.
(举个例子)。我很高兴跳过/忘记格式错误的行(即它的重要性只有 1/60000)。
第一次尝试是使用CSV.foreach
或类似的,并且简单地begin
rescue
next
end
跳过错误。没有骰子。我希望这个如此被接受的答案是更冗长一点:CSV.read 第 x 行中的非法引用 https://stackoverflow.com/questions/9864064/csv-read-illegal-quoting-in-line-x?rq=1(即“自己阅读文件”——我想我在下面尝试过)。
还有这个问答(如何进一步处理导致 Ruby FasterCSV 库抛出 MalformedCSVError 的数据行? https://stackoverflow.com/questions/7671127/how-can-i-further-process-the-line-of-data-that-causes-the-ruby-fastercsv-librar)似乎有希望,但接受的答案并没有......完全......在我看似相似的情况下工作(为了清晰起见而修改),通过 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