简体   繁体   中英

How to read blank lines in CSV file in Ruby

I am reading in a CSV file with Ruby and it works fine except if there are blank rows at the start. It seems to skip the blank lines and go straight to a line with content. I want to read the blank lines as I need to count the row numbers.

I use this function, which works fine except for skipping the blank rows:

CSV.foreach(params[:file].tempfile, headers: false, :encoding => 'ISO-8859-1') do |row|

I have a user input which dictates the starting row to read in, so I need to count down each row until I reach the desired row to read. I really do not want to tell the user to edit the csv file to make sure rows are not blank.

UPDATE:

OK, my question turned out to be a red herring. The actual problem was that I had an Excel file with blank lines at the start. When I saved as a CSV file from within Excel, the blank lines were being removed from the saved CSV file but the Excel view of the file, ie filename.csv, still showed the blank lines present. I only discovered this by re-opening the file in Excel or a text editor. (All posted comments helped give me the clues to find this).

So ... now I have a new problem ... why does Excel remove blank rows when saving as CSV?

OK, my question turned out to be a red herring. The actual problem was that I had an Excel file with blank lines at the start. When I saved as a CSV file from within Excel, the blank lines were being removed from the saved CSV file but the Excel view of the file, ie filename.csv, still showed the blank lines present. I only discovered this by re-opening the file in Excel or a text editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM