跳过CSV的前5行

编程入门 行业动态 更新时间:2024-10-27 20:24:03
本文介绍了跳过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行

本文发布于:2023-10-26 01:04:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528627.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:跳过   CSV

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!