Why does a four-line CSV have only three records?

2026-11-29来源 dev.toEnglish
Why does a four-line CSV have only three records?

Suppose a CSV importer sees four lines in a file and inserts two rows. A record may look missing. But if two of those physical lines form one quoted note, two data rows are exactly right. Matching row counts can still hide a separate bug: Python read the correct number of records while changing the line break inside a field.

01 · Read the same 42 bytes three ways

The comma-delimited UTF-8 fixture has a header and two IDs, 41 and 42. A double-quoted note on row 41 contains both a comma and CRLF (\r\n). We wrote the bytes to a temporary file and read that file three ways with Python 3.12.14. No production data or spreadsheet application was involved.

Reader Rows treated as records, including header Fields per row ID 41 note
Split lines, then split on commas 4 2, 3, 1, 2 Not preserved as one record
Default text mode + csv.reader 3 2, 2, 2 call, then\nemail
newline="" + csv.reader 3 2, 2, 2 call, then\r\nemail

The manual split does not track whether a quote is open. It treats the quoted comma as a column boundary and the embedded CRLF as a record boundary. RFC 4180 describes quoted fields that can contain commas and line breaks. It documents a common format, not a guarantee that every CSV exporter uses it. RFC 4180 §2

02 · Correct record count, different field value

Python's default text mode translates CRLF to LF. The CSV parser receives the text after that translation, so it can recover the record boundaries but cannot recover the original line ending inside the note. Opening with newline="" gives the parser untranslated line endings.

Both parsing paths returned three records, but default text mode produced LF and newline empty preserved CRLF inside the cell.

Both parsing paths returned three records, but default text mode produced LF and newline empty preserved CRLF inside the cell.

Figure · Same count, different value. The right side shows escaped values, not literal backslashes stored in the cell. For this fixture, reading without translation and writing with the same delimiter and quotes and the writer’s default CRLF produced the original 42 bytes. That is not a general byte-for-byte round-trip guarantee for other quoting styles, BOMs or dialects. Python csv · open newline behavior

03 · When a split works, and where the parser stops

On the simpler two-line fixture, id,note followed by 41,done, manual splitting and csv.reader agreed. A private format can rely on that shortcut if it forbids commas, quotes and line breaks inside values and enforces those constraints. Do not infer them from the extension of an external download.

Strict parsing does not check your schema. Below, the parser accepts a two-field header followed by a one-field row containing only 43, even with strict=True. Validate field counts, required fields and ID uniqueness separately.

04 · Separate parsing, validation and normalization

Open files using the expected encoding and newline="", and parse the producer’s delimiter and quoting rules. Then validate the header, row width and required fields. If the product expects LF inside notes, make that conversion deliberately after parsing and validation, and keep the source where it matters. Include a quoted comma, an embedded CRLF, and a short row in regression tests. Distinguish logical record and physical line positions in diagnostic output when possible.

공통 재현 코드 / Shared replay

import csv import sys from pathlib import Path from tempfile import TemporaryDirectory raw = b'id,note\r\n41,"call, then\r\nemail"\r\n42,done\r\n' expected = [["id", "note"], ["41", "call, then\r\nemail"], ["42", "done"]] with TemporaryDirectory() as tmp: path = Path(tmp) / "sample.csv" path.write_bytes(raw) with path.open(encoding="utf-8", newline="") as f: proper = list(csv.reader(f, strict=True)) with path.open(encoding="utf-8") as f: translated = list(csv.reader(f, strict=True)) naive = [s.split(",") for s in raw.decode().splitlines()] with path.open("w", encoding="utf-8", newline="") as f: csv.writer(f).writerows(proper) assert path.read_bytes() == raw print(sys.version.split()[0], len(raw), path.read_bytes() == raw) print("naive:", naive) print("translated:", translated) print("preserved:", proper) assert proper == expected and proper != translated assert len(naive) == 4 and len(proper) == 3 assert [len(r) for r in naive] == [2,3,1,2] assert translated[1][1] == "call, then\nemail" simple = 'id,note\r\n41,done\r\n' assert [s.split(",") for s in simple.splitlines()] == list(csv.reader(simple.splitlines())) bad_shape = list(csv.reader(["id,note", "43"], strict=True)) assert [len(r) for r in bad_shape] == [2,1] 

관측 / Observed: Python 3.12.14 · 42 bytes · byte round trip True. Manual split: 4 physical lines with 2, 3, 1, 2 fields. Both parser modes: 3 records, two fields each; default reads LF in the note, newline="" preserves CRLF. Simple fixture agrees; strict reader still accepts the short row.

原文:https://www.a8q9.cn/en/article/why-does-a-four-line-csv-have-only-three-records-6e310b.html

相关文章