Count CSV records without mistaking embedded newlines for new rows

A text editor shows five lines in an exported CSV, but a parser returns three data records. That can be correct. A quoted field may contain a line break, and the header is another record of its own. Before reporting that rows have disappeared, count the parsed records and preserve their locations in the source.

This distinction matters when a note, address or description occupies several lines. Cutting the file into pieces at every newline can detach the second half of a field and make it look like a separate entry.

Three colored paper strips lie across ruled lines; the blue strip bends across more than one line.
ImageGen illustration: one continuous record can occupy several physical lines. The paper shapes are a conceptual model.

A five-line file with three data records

Invented practice data: save the following as a UTF-8 file named sample.csv. The labels describe no real archive or investigation. The break between “North room” and “upper shelf” is an actual line break inside the quoted field, not the two characters backslash and n.

id,note
A,"North room
upper shelf"
B,"Desk, west"
C,"Box ""blue"""

The header occupies physical line 1. Record A occupies lines 2–3; B occupies line 4; C occupies line 5. A soft wrap caused by a narrow editor window does not create another physical line.

In B, the comma belongs to the note. In C, doubled quotation marks represent a quotation mark within the field, so the parsed note is Box "blue". The CSV format described in RFC 4180 permits quoted multiline fields and explains this escaping. The document is informational, and real exports can use different dialects.

Count records and print a source locator

Run this Python program in the directory containing the practice file. It expects exactly the two-column, comma-delimited format shown above. It reads the file without rewriting it and reports the record number, ID, first physical line and last physical line.

import csv

with open("sample.csv", encoding="utf-8", newline="") as source:
    reader = csv.reader(source, delimiter=",", quotechar='"',
                        doublequote=True, strict=True)
    header = next(reader, None)
    if header != ["id", "note"]:
        raise ValueError("Unexpected header; check the file format")

    count = 0
    while True:
        start_line = reader.line_num + 1
        row = next(reader, None)
        if row is None:
            break
        if len(row) != len(header):
            raise ValueError(
                f"Unexpected field count near line {reader.line_num}"
            )
        count += 1
        print(count, row[0], start_line, reader.line_num)

    print("Data records:", count)

The output for the fixture is:

1 A 2 3
2 B 4 4
3 C 5 5
Data records: 3

The program advances one parsed record at a time. Python’s csv reader documentation distinguishes line_num, the number of source lines consumed, from the number of records returned. Its reader instructions specify opening a file with newline="", leaving newline handling to the CSV module.

We checked this synthetic fixture locally with Python 3.12.10, including LF and CRLF line endings and a copy without a final newline. Each produced the three records and line ranges shown above. This is a parser check on a known example, not a test of any publisher’s dataset.

Make the counting policy explicit

This program excludes the verified header from the data count. It rejects an unexpected number of fields, including a blank record, instead of quietly skipping it. If your source legitimately permits blank records, define a separate policy and record how many you exclude. Do not confuse a blank physical line inside a quoted field with a blank record.

The strict=True setting raises errors for bad CSV input recognized by this parser; it is not a complete check of a publisher’s schema. Our extra width check catches a different issue: a parsed record with the wrong number of fields. If parsing stops with an error, the records printed so far are only a partial result. Do not report their count as the file’s total.

Before applying the method to another file, establish its encoding, delimiter, quote rules and header convention from the source or a verified sample. Do not switch delimiters merely until a convenient count appears. Preserve the original and record the chosen settings. If spreadsheet import also changes the identifiers, use the CSV identifier-preservation checks as a separate step.

Cite the record someone else can find

A useful locator for the exercise is “data record 1, ID A, physical lines 2–3 in sample.csv.” Add the source URL, retrieval time and file hash for a real export. A line number by itself can become ambiguous after re-exporting, reordering or reformatting a file.

Keep both numbers when explaining a discrepancy: “The supplied fixture has five physical lines, including its header, and three data records under the stated CSV settings.” That does not establish that a real export contains every record the publisher intended to release. Completeness requires another reference, such as a documented total for the same export scope.

For your next data handoff, attach the parser settings, header policy, record count and one inspected multiline example to the research report. A reviewer should be able to locate the field you quoted without reconstructing which meaning of “row” you used.

Author: OSINT Jet · Primary sources reviewed 4 December 2026