Converting Records Without Loading the Entire File

A stream-to-stream conversion can read one record, transform it, and write the output before reading the next.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two independent records
  2. Identify global requirements
  3. Measure the largest state retained between rows
  4. Design failure behavior for partial outputs

Trace two independent records

An exporter changing Celsius readings to Fahrenheit can convert each complete row separately. Memory need only hold the active record when no other rule requires history. See mapping each item.

Identify global requirements

Sorting all rows or deduplicating repeated keys needs additional state. A stream can still expose incremental output while an index retains the needed history. Grouping by keys shows what accumulates.[1]

Measure the largest state retained between rows

To convert thirty million measurements into rounded records, process each record and write it before reading a long backlog. If the transformation also needs a running count, retain just that count. Producing a globally sorted output requires more state or an external sort. See running totals.

Read row → decode → transform → emit
Retained state: current record, decoder and output buffer, total count
A list collecting every result defeats the intended memory bound

Design failure behavior for partial outputs

If a malformed row occurs late, a stream consumer may already see earlier results. A file-based atomic replacement can retain the prior output until all rows validate. Test a late error after several valid rows.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩