跳过CSV的前5行 [英] Skip first 5 lines of CSV

查看:83
本文介绍了跳过CSV的前5行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定这是微不足道的,但是经过一段时间的努力,现在是时候让您友好的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行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆