3

Hey. How can I get a total number of rows in a file (do not want to do it with loop). I'm reading CSV file.

Example 1

CSV.open('clients.csv', 'r')

Example 2

FasterCSV.foreach('clients.csv')

Thx.

xpepermint
  • 35,055
  • 30
  • 109
  • 163

1 Answers1

7

How large is your file?

This option loads the entire file into memory, so if there are size/memory concerns it might not work.

numrows = FasterCSV.read('clients.csv').size

This option uses Ruby's built-in CSV module, which as you know is quite slow, but it does work. It also loads the entire file into memory:

numrows = CSV.readlines('clients.csv').size

Both FasterCSV.read and CSV.readlines return arrays of arrays, so you can use any array magic you want on the results.

Roadmaster
  • 5,297
  • 1
  • 23
  • 21