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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With