Ruby CSV标头不在第一行 [英] Ruby CSV headers not in the first line

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

问题描述

我想使用(headers:true选项)读取CSV文件,但我的文件的前5行包含不需要的数据。

I would like to read CSV file with (headers: true option), but the first 5 lines of my file contain unwanted data. So I want line 6 to be a header and start reading file with line 6.

但是当我读取一个文件 CSV.readlines(my_file .csv,headers:true).drop(5)
它仍然使用行1作为标题。

But when I read a file CSV.readlines("my_file.csv", headers: true).drop(5), it still uses line 1 as a header. How can I set line 6 as a header?

推荐答案

在开始CSV之前预读垃圾行。

Pre-read the garbage lines before you start CSV.

require 'csv'

File.open("my_file.csv") do |f|
  5.times { f.gets }
  csv = CSV.new(f, headers: true)
  puts csv.shift.inspect
end

这篇关于Ruby CSV标头不在第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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