Reading a File Line by Line or All at Once

A line-based reader can process records as they arrive. Reading the entire file is useful when evaluation needs a bounded whole document.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Match memory to the operation
  2. Know where the format permits lines
  3. Identify the largest unit the parser retains
  4. Match logical record boundaries to the format

Match memory to the operation

Computing the sum of one value per line needs the current line and an accumulator. Retaining every line increases memory with file size. Time and space accounting separates retained state from total bytes processed.

Know where the format permits lines

A quoted CSV field can span physical lines, so a format-aware parser should decide when a record is complete. CSV quotes and newlines give an example where splitting first changes the meaning.[1]

Identify the largest unit the parser retains

An importer that reads plain one-line records can process one line at a time. Reading an entire large file first retains all bytes or decoded text together. A streaming parser can still use large memory if the file consists of one enormous line or the consumer accumulates all processed rows. See collection memory.

One million short lines: streaming can discard processed records
One enormous line: line buffer can itself grow large
Saving every parsed row increases retained memory in either strategy

Match logical record boundaries to the format

If quoted fields can span physical lines, stream using a parser that tracks quoting state. For complete-file operations, define a reasonable size budget and a clear rejection. Test both many small records and one unusually long record.

References

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