Ruby CSV headers not in the first line

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

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

+4
source share
2 answers

Read garbage lines before starting 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
+5
source

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
+2
source

Source: https://habr.com/ru/post/1584839/


All Articles