4

I have a CSV file that contains blank rows like this:

row A

row B
row C


row D

How should I proceed to remove those blank rows to have:

row A
row B     
row C  
row D

I found many topics on this subject for other languages but none in Ruby.

1

2 Answers 2

4

You don't have to delete the blank lines, just skip them:

require "csv" 

CSV.foreach("path/to/file.csv", skip_blanks: true) do |row|
  # handle row, it won't be blank
end
Sign up to request clarification or add additional context in comments.

Comments

3

Three simple steps:

data = File.read('data.csv')                       # Read the file
cleaned = data.gsub(/^$\n/, '')                    # Remove blank lines, from [1]
File.open('out.csv', 'w') { |f| f.write(cleaned) } # Write the cleaned data

[1] Remove empty lines from string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.