Product case study · November 24, 2026

Ask Claude Code to preserve line breaks inside CSV fields

Reproduce a CSV importer that silently joins multiline notes, then ask Claude Code for a scoped repair and verify LF and CRLF preservation with Python tests.

Reading time
6 min
Checked
Nov 24, 2026
A folded blue paper ribbon passes through a charcoal sorting frame into a cream record card while keeping its bends.
One record can contain several lines. Keep the boundaries inside it.
Bottom line

Test the field contents, not just the row count. Splitting CSV text into stripped lines can erase data before the CSV parser sees it.

A customer note says “Leave at reception” on one line and “Call on arrival” on the next. After import, it becomes Leave at receptionCall on arrival. The import finishes successfully. The number of records is right. The note is wrong.

This lab gives Claude Code a small repair with a precise acceptance test: preserve every character inside the parsed fields, including line breaks. It is useful when an importer already uses Python’s CSV module but still loses information.

You need Bash, Python 3, and an installed, signed-in Claude Code. The Python baseline and reference repair below were tested locally. The agent prompt is an authored exercise, not a recorded Claude session or a claim about its success rate. Official sources were checked November 24, 2026.

Reproduce the quiet data loss

Create an isolated practice folder and a broken importer:

csv_lab=$(mktemp -d /tmp/claude-csv-newlines.XXXXXX)
cd "$csv_lab"
cat > importer.py <<'PY'
import csv
from pathlib import Path


def read_notes(path):
    text = Path(path).read_text(encoding="utf-8")
    return list(csv.DictReader(text.splitlines()))
PY
python3 - <<'PY'
from pathlib import Path
from importer import read_notes

Path("notes.csv").write_bytes(
    b'id,note\n'
    b'101,"Leave at reception\nCall on arrival"\n'
    b'102,No special instructions\n'
)
rows = read_notes("notes.csv")
print(len(rows))
print(repr(rows[0]["note"]))
PY

The local baseline printed:

2
'Leave at receptionCall on arrival'

That second line is the failure. There should be a \n between the two instructions. Counting records cannot detect this loss.

Python’s str.splitlines() removes line endings unless asked to keep them. A CSV field may span physical lines, so those characters can be part of the data. Passing stripped lines to the parser has already removed something it needs. The CSV reference distinguishes physical lines from records and recommends opening CSV files with newline="".

Define what the repair must preserve

Save this as SPEC.md:

read_notes(path) reads a valid UTF-8 CSV with id,note headers and
returns a list of dictionaries in input record order.
Preserve parsed field strings exactly, including LF, CRLF, blank
lines within quoted notes, commas, quotes and non-ASCII characters.
Return an empty list for a header-only file.
Never write to the input. Use only the Python standard library.
Change only importer.py. Keep this specification and the tests fixed.

This exercise assumes a valid comma-delimited file with exactly two fields per record and no byte-order mark. It does not add schema validation, encoding detection or malformed-CSV recovery. If those are required for your import pipeline, give them separate acceptance cases. The site’s BOM header repair lab covers a different input-boundary problem.

Save this as test_importer.py:

import tempfile
import unittest
from pathlib import Path
from importer import read_notes


class NoteImportTests(unittest.TestCase):
    def check_import(self, payload, expected):
        with tempfile.TemporaryDirectory() as folder:
            source = Path(folder) / "notes.csv"
            source.write_bytes(payload)
            try:
                self.assertEqual(read_notes(source), expected)
            finally:
                self.assertEqual(source.read_bytes(), payload)

    def test_lf_and_blank_line_inside_note(self):
        self.check_import(
            b'id,note\n101,"Leave at reception\n\nCall on arrival"\n'
            b'102,No special instructions\n',
            [
                {"id": "101", "note": "Leave at reception\n\nCall on arrival"},
                {"id": "102", "note": "No special instructions"},
            ],
        )

    def test_crlf_inside_note(self):
        self.check_import(
            b'id,note\r\n101,"First line\r\nSecond line"\r\n',
            [{"id": "101", "note": "First line\r\nSecond line"}],
        )

    def test_quotes_comma_and_unicode(self):
        self.check_import(
            'id,note\n103,"Zoë said ""hello"", then left"\n'.encode("utf-8"),
            [{"id": "103", "note": 'Zoë said "hello", then left'}],
        )

    def test_header_only(self):
        self.check_import(b"id,note\n", [])

Run the baseline yourself:

python3 -m unittest -v test_importer

Locally, the two multiline tests failed; the quote/comma/Unicode case and header-only case passed. The fixtures use explicit bytes so the editor and operating system cannot silently change the intended line endings while you save the sample data.

The CRLF test matters even if you work on Linux. It specifies the characters inside the note, not a preferred newline convention for your machine.

Ask Claude Code for a bounded repair

Start claude in this practice folder. Paste:

Read SPEC.md, importer.py and test_importer.py.
Run python3 -m unittest -v test_importer and report the baseline.
Trace where LF and CRLF characters are lost before parsing.
Change only importer.py to satisfy the existing tests and specification.
Do not modify tests, normalize note contents, install packages,
commit, delegate or edit files outside this practice folder.
Run the same tests afterward. Report actual results and the changed lines.
Explain why checking only record count would miss this bug.

Anthropic’s common workflows describes giving Claude reproducible bugs and using tests to check repairs. Review the commands and edits under your active permission settings. The requested file boundary is an instruction; it does not itself isolate the process.

If the agent replaces line breaks with spaces, reject that patch: it changes the data contract. If it weakens the expected values in the tests, restore those values before assessing the importer. If it reports green tests without command output, rerun the command in your own terminal.

Review the reference patch

A small repair feeds the open text stream directly to the CSV reader:

import csv


def read_notes(path):
    with open(path, encoding="utf-8", newline="") as stream:
        return list(csv.DictReader(stream))

All four tests passed locally with this implementation. It consumes the reader while the file is still open, then returns the parsed records.

There are two changes to inspect: removing the line-splitting step and disabling newline translation on the file stream. Python’s text I/O documentation explains that newline=None translates recognized line endings to \n during reading; newline="" leaves them untranslated. That distinction is why a repair that merely swaps in splitlines(keepends=True) after the original read_text() still fails the exact CRLF requirement.

If your input is already an in-memory string, an io.StringIO(text, newline="") stream can supply it to the reader. But a stream wrapper cannot recover line endings an earlier step already stripped or normalized. Check the path that produced the string before declaring the import fixed.

Verify the result and recover the source

Exit Claude, rerun the four tests, then rerun the demonstration from the first section. The first note should now display as:

'Leave at reception\nCall on arrival'

Use repr() when inspecting these fields: printing a note normally turns its embedded line break into a display break, making character-level comparisons harder. The tests compare complete dictionaries, so they also check the second record, field names and order rather than accepting a plausible-looking first value.

If the tests unexpectedly pass before the repair, check that you are importing this folder’s broken implementation:

python3 -c 'import importer; print(importer.__file__)'

If the repaired reader still sees joined text in a real export, inspect an untouched source copy. A file that already contains receptionCall has no marker telling the importer where the break belonged. Re-export it from the authoritative source; inserting guessed spaces or line breaks would be another data transformation.

For a large production feed, this lab’s list-returning API also needs a separate memory review. The exercise proves field preservation on these fixtures; it does not establish production throughput or validate every CSV dialect.

Sources

Checked November 24, 2026:

Put this to work

How text preprocessing can corrupt a valid CSV without changing its record count.

Try

Repair one Python CSV reader in a disposable folder using a bounded Claude Code prompt.

Prove it worked

Run the same four tests against the broken reader and the reference repair.

Keep in view

  • Reproduce an importer that joins two lines of a customer note.
  • Give Claude Code exact field-preservation tests before requesting a patch.
  • Check both LF and CRLF, quoted commas, record order and unchanged source bytes.
Learn the workflow: Start a scoped Claude Code project session