๐งน Data Cleaning ยท 9 min read
CSV File Has the Wrong Number of Columns? Find the Broken Row
Almost always there is one row with an extra delimiter, and the fix is to find its line number rather than to rewrite the file. A comma inside a description field that never got wrapped in quotes looks exactly like a column separator to the parser. So does a quote that opened in one row and closed three rows later. Either way the tool reports a column-count mismatch and stops, because it has no way to know which of its readings is the wrong one.
This is common enough that the error text differs by tool while the cause does not: Expected 5 fields in line 12, saw 7 from pandas, "The number of columns is inconsistent" from Power Query, a truncated last column in Excel. The row number is the only part of those messages worth acting on.
The Rule the Parser Is Enforcing
RFC 4180, the closest thing CSV has to a specification, is short and specific. Each record sits on its own line, terminated by CRLF. Fields are separated by commas. If a field contains a comma, a line break or a double quote, the whole field must be enclosed in double quotes, and an embedded double quote is written as two double quotes in a row.
That last part is the one people trip over. A single unescaped double quote inside a quoted field does not mean "this is a quote character" to a lot of parsers. It means "the quoted section ends here", which flips the quoting state for everything that follows. Commas that were safely inside text become separators again, and the record balloons.
Three Causes, in the Order Worth Checking
1. An unquoted comma in a text field
A product name like Widget, large in a comma-delimited file adds one field. A mailing address with a suite number adds one more. If the exporter wrote text straight into the file without quoting, every such cell is a landmine, and the first one to appear is usually the row the error names.
2. A quote that opens and never closes
Look for an odd number of double quotes on the offending line. An unclosed quote at row 40 will make the parser swallow rows 41, 42 and 43 into one enormous field, which is why the reported line number and the visible damage are often several lines apart. If the number of quote characters in a line is odd, that line is your suspect even when the tool points somewhere else.
3. A ragged export
Some systems write a trailing comma on every row, which produces one empty extra column. Others write fewer fields on the final record because the last value was null and the writer skipped it instead of writing an empty string. Both cases produce a mismatch without any quote involved, and both are harmless once you know that is what they are.
Find the Line Number in One Pass
You do not need to open the file. Count fields per line and print the ones that disagree with the header. On Linux or macOS, with a five-column file:
awk -F, 'NF!=5 {print NR": "NF" fields"}' orders.csv | head -20That is a naive count, and it is wrong for any line containing a quoted comma, which is exactly the kind of line you are hunting. Use it as a first pass to see whether the file is broadly consistent or ragged all over, then confirm the suspects by eye:
awk -F, 'NF!=5 {print NR": "$0}' orders.csv | head -5 | cut -c1-200In Python, the same check with a real CSV parser, which respects quoting, and with the error caught so the line number survives:
import csv
with open("orders.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
width = len(header)
for row in reader:
if len(row) != width:
print(reader.line_num, len(row), row[:3])
reader.line_num gives the physical line in the file, not the record index, so if a field contains a quoted line break the two numbers differ. Trust the physical line when you go to edit.
Fix the Row, Not the Symptoms
Once you know which line is wrong, the repair is small. If the extra comma belongs to the text, wrap that field in double quotes and double any internal quotes. If it is a stray character from a bad export, delete it. If the record simply has fewer fields than the header, pad it with empty values so the columns line up, rather than letting the last field absorb three others.
When the damage is broad, say a column of free-text comments that was exported unquoted, re-export with quoting turned on instead of patching rows one at a time. Every spreadsheet and database export dialog has that option; it is usually labelled "quote all text cells" or similar. One clean re-export beats forty manual edits, and it keeps the file valid for the next tool that reads it.
A word of caution on the tempting shortcut. pandas will accept on_bad_lines="skip", and every loader has an equivalent. It works, and it also deletes complete records without telling you which. Print the bad lines first, confirm they are duplicate headers or blank rows, then drop them deliberately. The pandas-specific walkthrough covers the parameter list if you are working in a notebook.
When the Column Count Is Legitimately Too High
Occasionally the file is fine and the tool is the problem. Excel caps a worksheet at 16,384 columns and 1,048,576 rows, according to Microsoft's published Excel specifications, so a wide export loses columns on open with no warning beyond a truncation you may not notice. Sparse wide files, the kind produced by one-hot encoding or a pivot with hundreds of measures, hit that ceiling easily. The column limit page has the numbers and the workarounds; if the problem is rows rather than columns, start with the row limit or split the file with the CSV splitter.
If the file came from a spreadsheet that was saved carelessly, check for the other classic damage before you spend time on structure: a UTF-8 file reopened in a legacy encoding shows up as garbled text rather than a column error, and the garbled CSV fix covers that separately.
Frequently Asked Questions
Why does my CSV have a different number of columns than my header row?
One record contains an unquoted comma, or a quote character that was never closed. RFC 4180 requires any field containing a comma, a line break or a double quote to be wrapped in double quotes. Break that rule and the parser splits text into extra fields, and everything after the break shifts one column to the left or right.
How do I find the line with the wrong number of fields without opening the file?
Count delimiters per line. awk -F, 'NF!=5 {print NR, NF}' file.csv prints every line number whose field count is not five, in one pass, without loading the file into a spreadsheet. Replace 5 with your real header width.
Should I just skip the bad lines?
Only after you have counted what you are dropping. on_bad_lines="skip" makes the error vanish and deletes whole records quietly. Print them, check that they are duplicated headers or blank lines, then drop them on purpose.
Why does the same file open fine in one tool and fail in another?
Parsers infer the schema differently. Some read a sample and then reject any row wider than what they saw; others expand the schema to fit the widest row. One oversized row therefore opens cleanly in a lenient tool and fails in a strict one. The row number in the message matters more than the wording.
Can a CSV have more than 16,384 columns?
The file can, because CSV sets no column limit. Excel stops at 16,384 columns and 1,048,576 rows per Microsoft's specification, so a wider file loses data when Excel opens it. If the dataset genuinely needs more, change tools rather than reshaping the file.
See Which Column Breaks First
The analyzer reports the real field count per row and flags the ones that do not match, without sending your file anywhere.
Related reading
Data Cleaning โ other guides that pair well with this one.
- Excel Says the File Format and Extension Don't Match. What Now?
- CSV Files Lose Formatting After Save: Leading Zeros, Dates, Long Numbers
- Alteryx "Too Many Fields in Record" on a CSV: Causes and Fixes
- CSV to TXT: What Converting to Plain Text Actually Means
Browse all guides in the NoCodeCSV blog.