Check CSV quoting and record widths with Python
Reports the data-record count or raises an error for quoting or field-count problems. Record numbers count parsed records, so a quoted newline is part of its record.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place input.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 - <<'PY'
import csv
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.reader(source, strict=True)
headers = next(reader, None)
if not headers:
raise ValueError("Expected a nonempty header")
count = 0
for record, row in enumerate(reader, start=2):
if len(row) != len(headers):
raise ValueError(f"Record {record}: expected {len(headers)} fields, got {len(row)}")
count += 1
print(f"Checked {count} data records; quoting and widths accepted")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- This checks the Python CSV dialect, not every vendor dialect. It does not enforce required values, column types, uniqueness or allowed-value rules.
Documentation: Python CSV reader and writer