Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific rows in CSV files? [duplicate]

For example, maybe I want to start from the 5th row:

csv_text = File.read(file)
csv = CSV.parse(csv_text, :headers => true)
csv[20..-1].each do |row|

end

Is it possible to write something like csv[5..-1], from the 5th to the last row?

like image 815
cqcn1991 Avatar asked Sep 02 '25 15:09

cqcn1991


1 Answers

You can use the CSV.foreach method to iterate over the CSV and the with_index method to count the rows you read and skip rows you don't want to process. For example:

require 'csv'

CSV.foreach(file, headers: true).with_index(1) do |row, rowno|   
  next if rowno < 5 # skips first four rows
  # process the row
end

In Ruby 1.9.3 this wouldn't work since foreach doesen't return an Enumerator if no block is given. The code can be modified like this:

CSV.to_enum(:foreach, file, headers: true).with_index(1) do |row, rowno|
  # ...
end
like image 136
toro2k Avatar answered Sep 05 '25 16:09

toro2k