marcamillion marcamillion - 2 months ago 6
Ruby Question

How do I detect if a CSV is empty or has no rows?

I have an array

info
, where I am reading each item and adding it to a CSV file like so:

info.each do |listing|
CSV.open(csvfile, "a+") do |csv|
csv << listing
end
end


However, what I want to do is when the CSV is empty (i.e. this is the first row being added to this specific CSV) I will add a header first before adding any data. A header being a row that just has data-categories: First Name, Last Name, Address, etc.

If I add it to that loop, it will add it after each record.

Also, there is no guarantee that the first item in the array will be the first item in the CSV. The CSV could be empty by the time the iterator is at
i[10]
for example.

How do I approach this?

Answer

You can check whether the CSV::Table contains any rows:

require 'csv'
filepath  = File.join('.', 'test')
csv       = CSV.open(filepath, 'wb', col_sep: ';', quote_char: "\x00")
csv_table = CSV.table(filepath)
csv_table.count
#=> 0