Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby CSV headers not in the first line

Tags:

ruby

csv

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?

like image 337
arthur-net Avatar asked Apr 27 '15 07:04

arthur-net


2 Answers

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
like image 132
Amadan Avatar answered Nov 14 '22 23:11

Amadan


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
like image 33
arthur-net Avatar answered Nov 14 '22 23:11

arthur-net