我敢肯定这是微不足道的,但是经过一段时间的努力,现在是时候让您友好的SO伙伴拯救我了.
I'm sure this is trivial but after an age pulling my hair out it's time for you friendly SO folks to save me.
我要对正在使用CSV类读取的CSV文件进行操作,如下所示:
I want to operate on a CSV file that I'm reading with the CSV class as follows:
CSV.foreach(@path_to_file) do |row| #doing stuff here end但是文件头上方有5行需要删除(foreach方法遇到这些行时会倒钩).
However the file has 5 lines above the header that needs to be removed (the foreach method barfs when it encounters these lines).
我猜想我可以读取文件并重新组装而无需前5行,但是我敢肯定有一种更优雅的方法.
I'm guessing I can read the file and reassemble without the first 5 lines but I'm sure there's a more elegant way of doing this.
CSV方法不起作用的原因是,在前5行中是CSV类不喜欢的字符;它返回CSV:MalformedCSVError: Illegal quoting in line 3.
The reason the CSV methods don't work is that in the top 5 lines are characters that the CSV class doesn't like; it returns CSV:MalformedCSVError: Illegal quoting in line 3.
因此,我认为除非可以在尝试解析CSV之前将其删除,否则我无法使用CSV类.
So I don't think I can use the CSV class unless I can get it to remove the lines before it tries to parse the CSV.
推荐答案通过从不兼容的数据中构造有效的CSV字符串,您应该能够绕过CSV模块:
You should be able to bypass the CSV module by constructing a valid CSV string from your otherwise incompatible data:
CSV.parse(File.readlines(path).drop(5).join) do |row| # ... end更多推荐
跳过CSV的前5行
发布评论