How can I detect short or extra fields in CSV rows?
Quick answer
Read the header with Python’s csv.reader and use its number of fields as the expected count. Then check each parsed row and report any whose field count differs. Use the CSV parser rather than splitting lines on commas, since quoted fields can contain commas or newlines. The example only reads the file and reports irregular rows; it does not alter the input.
The question, the details, the next step.
A practical checklist
Confirm whether the first parsed record is a header.
Set the expected field count from the header or a known schema.
Use
csv.readerwith settings that match the file; do not split raw lines on commas.Compare
len(row)with the expected count for each parsed record.Report parsed-record numbers and, when useful,
reader.line_numseparately.Review flagged records in the original file before making any edits.
A few more useful answers
Does a matching field count prove that a CSV row is valid?
No. This check only compares the number of parsed fields with the expected count. It does not validate field contents or confirm that values are in the right columns.
Why can the source line count differ from the record number?
A quoted field can contain a newline, so one parsed record may span multiple physical source lines. reader.line_num counts source lines consumed, not parsed records. [S1]
Will this script fix rows with extra or missing fields?
No. It only reports field-count mismatches and does not write to the CSV. Review the original records before deciding how to handle them.
Sources
References used for this guide.
- [S1] Python 3.14 csv — CSV File Reading and Writing docs.python.org · Checked
