Product case study · November 25, 2026
Ask Claude Code to catch CSV rows that do not fit
Repair a Python CSV importer with Claude Code. Reject short and long rows while preserving empty cells, quoted commas and multiline values.

A parsed CSV row can still violate your import contract. Check its field count before accepting it, and keep empty cells distinct from absent fields.
Your import expects three columns. One record arrives with two; another has four. Python reads both without complaining, and the application carries on with data that does not fit its contract.
This is a useful Claude Code repair exercise because “make the CSV parser stricter” is an incomplete instruction. The agent needs to know whether an empty cell is allowed, what the header must be, and whether to reject the whole import when a later record is malformed.
Use Bash on Linux, macOS or WSL, Python 3, and an installed, signed-in Claude Code. All data below is fictional. The Python baseline and reference repair were tested locally; the agent prompt is an authored exercise, not a recorded Claude session. Official sources were checked November 25, 2026.
See what the importer accepts
Create a disposable practice folder:
csv_lab=$(mktemp -d /tmp/claude-csv-width.XXXXXX)
cd "$csv_lab"
cat > importer.py <<'PY'
import csv
import io
def read_contacts(text):
return list(csv.DictReader(io.StringIO(text, newline=""), strict=True))
PY
python3 - <<'PY'
from importer import read_contacts
print(read_contacts("id,name,note\n001,Ada\n002,Bo,hello,extra\n"))
PY
The baseline prints:
[{'id': '001', 'name': 'Ada', 'note': None}, {'id': '002', 'name': 'Bo', 'note': 'hello', None: ['extra']}]
Python’s DictReader reference documents this behavior: surplus fields go under restkey, while missing values use restval. Both default to None. Even with strict=True, our example accepts both widths. That option catches parser errors; it does not define your table’s schema.
The fixture uses io.StringIO, an in-memory text stream, so the exercise needs no real customer file or disk import. Its newline="" setting leaves newline handling to the CSV reader.
Define the difference between empty and absent
Save this as SPEC.md:
read_contacts(text) returns a list of dictionaries whose values are strings.
Require exactly this header, in this order: id,name,note.
Reject missing, duplicate, reordered or additional header columns with ValueError.
Each nonblank data record must contain exactly three fields.
Reject short and long records with ValueError; do not silently pad or truncate.
An explicit empty cell is allowed: 001,Ada, has three fields.
Preserve leading zeros, quoted commas and quoted newlines.
Ignore completely blank lines, but treat ,, as a real three-field record.
A valid header with no data returns an empty list. Empty input is invalid.
If any record is invalid, raise rather than return a partial result.
Use the Python standard library. Change only importer.py.
Keep this specification and the tests unchanged.
That is a deliberately small import policy. It allows empty names and IDs because this lab checks structure. A production importer may need a second layer of required-value checks.
Save the acceptance tests as test_importer.py:
import unittest
from importer import read_contacts
class ImportTests(unittest.TestCase):
def test_preserves_cells_and_quoting(self):
text = 'id,name,note\n001,"Ada, A.","first\nsecond"\n002,Bo,\n'
self.assertEqual(read_contacts(text), [
{"id": "001", "name": "Ada, A.", "note": "first\nsecond"},
{"id": "002", "name": "Bo", "note": ""},
])
def test_rejects_short_record(self):
with self.assertRaises(ValueError):
read_contacts("id,name,note\n001,Ada\n")
def test_rejects_long_record(self):
with self.assertRaises(ValueError):
read_contacts("id,name,note\n001,Ada,hello,extra\n")
def test_rejects_bad_headers(self):
for header in ("", "id,name", "id,name,name",
"name,id,note", "id,name,note,extra"):
with self.subTest(header=header):
with self.assertRaises(ValueError):
read_contacts(header + "\n")
def test_blank_lines_and_header_only(self):
self.assertEqual(read_contacts("id,name,note\n"), [])
self.assertEqual(read_contacts("id,name,note\n\n,,\n"), [
{"id": "", "name": "", "note": ""},
])
def test_late_failure_rejects_import(self):
with self.assertRaises(ValueError):
read_contacts("id,name,note\n001,Ada,ok\n002,Bo\n")
Run the fixed suite:
python3 -m unittest -v test_importer
The baseline runs six methods and reports eight failures, counting the five bad-header subtests separately. The quoted-content and blank-line tests pass already. Keep those passing cases: they protect behavior a quick string-splitting repair could destroy.
Ask Claude to repair the contract
Start claude in the practice folder and paste:
Read SPEC.md, importer.py and test_importer.py.
Run python3 -m unittest -v test_importer and record the baseline.
Explain why strict=True still accepts short and long rows.
Change only importer.py to satisfy the specification.
Keep tests and SPEC.md unchanged. Do not install packages, commit or delegate.
Use the CSV parser, not splitlines() or split(',').
Run the unchanged suite again and report its actual result.
Explain how an empty final cell differs from an absent field,
and how a failure after a valid row avoids returning partial results.
Anthropic’s common workflows recommends giving Claude reproduction details and having it verify a bug fix. Here the fixed tests make “verify” concrete. Review the active permissions and proposed commands; a prompt’s file boundary is an instruction, not a filesystem sandbox.
Review a reference repair
One implementation checks each parsed row before building its dictionary:
import csv
import io
FIELDS = ["id", "name", "note"]
def read_contacts(text):
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
if next(reader, None) != FIELDS:
raise ValueError("expected header: id,name,note")
contacts = []
for row in reader:
if row == []:
continue
if len(row) != len(FIELDS):
raise ValueError(
f"record ending at line {reader.line_num}: "
f"expected 3 fields, got {len(row)}"
)
contacts.append(dict(zip(FIELDS, row)))
return contacts
The reference repair passed all six methods locally. An empty final cell remains an empty string. An absent final field makes the parsed list too short. The width check happens before zip, so dictionary construction cannot quietly discard surplus fields.
The exact-header rule also prevents two columns from sharing one dictionary key. It intentionally rejects a reordered export; if your application permits column reordering, change the contract and add tests before changing the implementation.
Python’s CSV reader documentation distinguishes physical lines from records: quoted values can span multiple lines. That is why the error says “record ending at line” rather than claiming to identify a record number.
The function builds its list locally and returns only after the loop finishes. A late exception returns no list. That guarantee does not cover a different importer that writes each row to a database as it reads; that design needs its own transaction policy.
Check the result yourself
Exit Claude and rerun the test command. Review importer.py alongside the original specification.
- If short rows pass, look for default padding that masks absent fields.
- If long rows pass, look for slicing or unchecked dictionary construction that drops values.
- If
001,Ada,fails, the repair may be confusing an empty string with an absent field. - If quoted content fails, look for manual comma or line splitting.
- If imports fail, run from the folder containing both Python files.
A passing run proves the supplied structural cases. It does not validate email addresses, deduplicate contacts, bound memory usage, or sanitize spreadsheet formulas. This function takes the whole text and returns a whole list; plan separately for large imports.
Keep the short-row test next to the explicit-empty-cell test. Their difference is one comma, but it is the difference your importer needs to preserve.
Sources
Checked November 25, 2026:
- Python: CSV reading and writing — reader behavior, missing and extra fields, strict parsing and physical line counts.
- Python: in-memory text streams —
StringIOand newline handling for the local fixture. - Anthropic: common workflows — reproduce, repair and verify a bug with Claude Code.
Put this to work
Why CSV parsing and row-shape validation are separate checks.
Try
Give Claude Code a fixed import contract and six local test methods.
Prove it worked
Compare the baseline failures with the reference repair using unchanged tests.
Keep in view
- Reproduce a CSV import that silently accepts short and long rows.
- Keep an empty cell distinct from a missing field.
- Verify the repair without breaking quoted commas or multiline values.