Parse a Labelled CSV and Report Invalid Rows
Check labelled CSV data for a valid header, missing text and unknown categories while preserving diagnostic line numbers.
Difficulty Beginner
Prepare synthetic input
Use Python 3 and a text editor. Save the following as sample.csv. The quoted comma is part of the message text.
text,label
"Thanks, I found it",resolved
Where is the manual?,open
,open
I have a question,unknown
Validate rows
Save as check_csv.py and run python3 check_csv.py. Work in the same directory as the CSV.
import csv
from pathlib import Path
def validate(path):
problems = 0
with path.open(encoding="utf-8", newline="") as source:
reader = csv.DictReader(source, strict=True)
if reader.fieldnames != ["text", "label"]:
raise ValueError("Expected the header text,label")
for row in reader:
if None in row or not (row["text"] or "").strip():
print(f"Line {reader.line_num}: invalid text or column count")
problems += 1
elif row["label"] not in {"resolved", "open"}:
print(f"Line {reader.line_num}: invalid label")
problems += 1
return problems
try:
invalid = validate(Path("sample.csv"))
except (OSError, ValueError, csv.Error) as error:
raise SystemExit(f"Cannot read dataset: {type(error).__name__}")
print(f"{invalid} invalid rows")
raise SystemExit(bool(invalid))
Check the result
Expect errors for the last two data rows. newline="" lets the CSV module handle embedded line breaks and commas. For multiline records, line_num gives the physical line ending the record. The script records the reason without logging the original message.
Troubleshooting and practice
If the header looks right but validation fails, check for an unexpected Unicode byte-order mark, delimiter or header spacing using a trusted editor. Use utf-8-sig only when your input contract allows that prefix. Add an extra unquoted comma in a new row and check that the row is rejected. Limit file size in automated workflows and keep potentially identifying text out of diagnostics.