加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在CSV文件中跳过标题前的行

发布时间:2020-12-17 02:55:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to skip the first line of a CSV file and make the second line the header????????????????????????????????????5个 我试过搜索,但找不到有关我的问题的问题.假设我有一个看起来像这样的CSV文件: Metadata line 1Metadata line 2Metada
参见英文答案 > How to skip the first line of a CSV file and make the second line the header????????????????????????????????????5个
我试过搜索,但找不到有关我的问题的问题.假设我有一个看起来像这样的CSV文件:

Metadata line 1
Metadata line 2
Metadata line 3
Metadata line 4
foo,bar,baz
apple,orange,banana
cashew,almond,walnut

行foo,baz是标题,以下行是相应的数据.当我像这样编写我的ruby代码时:

CSV.foreach("filename.csv",:headers=>true) do |row|
  puts "#{row}"
end

它显然打破了.在标题之前跳过这些行的最佳方法是什么?目前我在想我可以这样做:

Find the first row with commas and get line number
Extract that line as an array
Pass that array to :headers

但这感觉很麻烦 – 如果我确切地知道标题是什么行,那么跳到该行并忽略之前的所有内容的最佳方法是什么?这可能吗?如果这是一个之前被问过的问题,我会高兴地吞噬这些答案,也许我的搜索功能还不够好.

非常感谢!

解决方法

CSV有一个skip_lines选项.不完全清楚它是否会跳过标题行或只是行,但值得一试.

:skip_lines – When set to an object responding to match,every line matching it is considered a comment and ignored during parsing. When set to a String,it is first converted to a Regexp. When set to nil no line is considered a comment. If the passed object does not respond to match,ArgumentError is thrown.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读