How can I count CSV records while ignoring blank rows?
Quick answer
Use Python’s csv.reader and count each parsed row that is nonempty: if row: count += 1. Open the file with newline=''. This ignores empty parsed rows but keeps rows made of empty fields, such as the two-field row represented by ,. Counting physical lines can be wrong because a quoted CSV field may contain a newline and still belong to one record. [S1]
The question, the details, the next step.
A practical checklist
Open the file with
newline=''and usecsv.reader.Count parsed rows rather than physical lines.
Use
if rowto skip empty parsed rows while keeping rows containing empty fields.Decide whether the header belongs in your count; if not, skip the first nonempty parsed row.
Set the reader’s dialect appropriately if the file does not use the defaults.
A few more useful answers
Does `if row` remove a row containing only empty fields?
No. A parsed row such as ['', ''] is a nonempty list, so if row keeps it. That is different from an empty parsed row, represented by an empty list.
Should I use `newline=''` when opening the file?
Yes. The Python documentation recommends it so the CSV module handles newlines correctly, including newlines inside quoted fields. [S1]
Does this count the header?
The basic count includes every nonempty parsed row, including a header. Skip the first nonempty row if your goal is to count data records only.
Sources
References used for this guide.
- [S1] Python 3.14 csv module: reader behavior, dialects, and line handling docs.python.org · Checked
