Read multiline CSV records and source line ranges in Python
Read order notes containing commas and line breaks, report their physical line ranges, and check malformed files with a working example.
In this article
When an order spans two lines
A customer adds a delivery note to an order. An address line and a door instruction occupy the same exported field on separate lines. The CSV remains valid when the exporter surrounds the entire note with quotes. A line-based counter can overstate the number of orders, and splitting each line on commas can interpret punctuation inside the note as a field separator. This example uses Python to read a small file with three orders. Its notes contain a comma, a real line break, and an intentionally empty field. The reader also reports the physical lines occupied by each record. That range helps a support team locate an import problem without copying the customer’s note into a log entry.
Open the file without rewriting its newlines
Open the text file with UTF-8 encoding and pass an empty string for newline. The CSV reader then receives line endings directly. The CRLF inside the quoted example survives in the note value. If a downstream system needs a different convention, normalize the parsed note in a separate step with an explicit rule. This example uses the standard comma-separated dialect. Choose a delimiter or quoting convention from the data contract when working with another exporter. The header check compares the two column names in their expected order. A revised export template that adds a third column will therefore surface as an incompatible input before any order reaches the import stage.
Track the source range for each record
Before asking for the next record, add one to the reader’s current physical line count. After the call, line_num reports the last source line consumed. The generator yields the order ID, its note and the two line numbers. The sample writes the file to a temporary directory. It reports lines 2–2 for A17, 3–4 for A18 and 5–5 for A19. The middle order counts once, because the reader consumes the continuation line before encountering the closing quotation mark. The comma in the first note and the empty third note also survive parsing. In a real import, retaining those ranges with the file revision makes a disputed row straightforward to locate.
import csv
from pathlib import Path
def read_orders(path):
with path.open(encoding="utf-8", newline="") as stream:
reader = csv.reader(stream, strict=True)
if next(reader, None) != ["order_id", "note"]:
raise ValueError("expected order_id,note header")
while True:
start = reader.line_num + 1
try:
row = next(reader)
except StopIteration:
return
except csv.Error as exc:
raise ValueError(f"invalid CSV near lines {start}-{reader.line_num}") from exc
if len(row) != 2 or not row[0]:
raise ValueError(f"invalid order on lines {start}-{reader.line_num}")
yield row[0], row[1], start, reader.line_num
if __name__ == "__main__":
import tempfile
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "orders.csv"
path.write_bytes(b'order_id,note\r\nA17,"door, left"\r\nA18,"first\r\nsecond"\r\nA19,\r\n')
rows = list(read_orders(path))
assert rows == [
("A17", "door, left", 2, 2),
("A18", "first\r\nsecond", 3, 4),
("A19", "", 5, 5),
]
print([(order, first, last) for order, _, first, last in rows])
for data, expected in [
(b'order_id,note\nA18,"never closed', "2-2"),
(b'order_id,note\nA18,one,two\n', "2-2"),
(b'order_id,note\n,blank key\n', "2-2"),
(b'wrong,note\nA18,ok\n', "expected order_id,note header"),
]:
path.write_bytes(data)
try:
list(read_orders(path))
except ValueError as exc:
assert expected in str(exc), str(exc)
else:
raise AssertionError("invalid file was accepted")
print("Five checks passed")
Recognize syntax and schema failures
With strict parsing enabled, an opening quote without its closing partner raises csv.Error in the sample. We attach the starting line and the reader’s final consumed line to the reported failure. A row with three fields is valid CSV syntax but fails the import schema. We check the field count separately so that both cases surface. The order identifier must contain a value, while the note may be empty. The checks at the end of the program exercise those cases and a wrong header. In production logs, a file ID, a line range and an error category give investigators enough information to open the right source without spreading note contents across monitoring tools.
Decide what a failed file can change
The generator yields complete records one at a time. A failure near the end can occur after its consumer has received earlier orders. Decide how much is committed before putting a durable write inside the loop. With small files, reading and validating all records first and inserting them in one database transaction is straightforward. With large files, stage the data under an import ID and promote it after the final record passes. A file digest can help recognize retries for the same original bytes. Duplicate order IDs and updates to an existing note require their own policies. The parser reports each input record and leaves these business decisions to the importing application.
Verify the original export during an investigation
Compare the reported range with the original export revision. Spreadsheet software may change line endings and quoting when it saves a new copy. The parser in this example treats a blank physical line as a row with an invalid shape. A producer contract that permits empty spacer rows needs an explicit rule and a corresponding test. Document the file size and supported encoding alongside the expected header. When the import code changes, run the tiny fixture with a comma, a multiline field and an empty note first. Then confirm a malformed file fails in the right stage and that any records already validated follow the application’s transaction policy.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment