Andrey Deineko
Andrey Deineko

Reputation: 52357

Can't remove empty rows from CSV

I have empty rows in cvs file:

CSV.table(filepath).count { |row| row.to_h.values.all?(&:blank?) }
#=> 6

I am trying to delete these using CSV::Table#delete_if:

CSV.table(filepath).delete_if { |row| row.to_h.values.all?(&:blank?) }
#=> #<CSV::Table mode:col_or_row row_count:6>

Here I would expect my csv to no longer contain empty rows, but:

CSV.table(filepath).count { |row| row.to_h.values.all?(&:blank?) }
#=> 6

Am I missing some point here? I checked if CSV::Table has something like delete_if!, but it does not, so assumingly what I have should work.

Upvotes: 1

Views: 449

Answers (2)

steenslag
steenslag

Reputation: 80065

CSV.table(filepath, skip_blanks: true)

causes CSV to ignore empty rows.

Upvotes: 0

Milan K&#246;pke
Milan K&#246;pke

Reputation: 1133

The documentation of delete_if states:

This method returns the table for chaining.

So you get the table back and I guess you are expected to save it to some CSV then again. It does not modify the original CSV file.

You need to store it then again: File.write('/path/new_name.csv', csv.to_s)

Upvotes: 5

Related Questions