arthur-net
arthur-net

Reputation: 1216

Ruby CSV headers not in the first line

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.

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?

Upvotes: 6

Views: 2311

Answers (2)

arthur-net
arthur-net

Reputation: 1216

Here is my solution

require 'csv'

my_header = CSV.readlines("my_file.csv").drop(5).first

CSV.readlines("my_file.csv", headers: my_header).drop(6) do |row|

 do something .....
end

Upvotes: 4

Amadan
Amadan

Reputation: 198304

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

Upvotes: 8

Related Questions