Detecting End of File Without Losing a Record

An input API signals when no more data is available. Detect that signal separately from ordinary empty fields and short final records.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read a final line
  2. Report a truncated record
  3. Keep a last record lacking its final newline
  4. Distinguish an empty line from no returned data

Read a final line

For a file whose last line contains done without a terminator, Python's line read returns that text and a later read returns the empty end marker. A blank line with a terminator instead includes a newline. See line iteration.

Report a truncated record

If a header promises more payload bytes, exhaustion before that length is a malformed record. Length framing distinguishes clean end between records from premature end within one.[1]

Keep a last record lacking its final newline

Reading A\nB line by line yields a first line A with its terminator and a final nonempty line B. End of file follows after B has been returned. If the code only processes lines ending in a newline it discards B, even when the format allows that final record. See iterating over lines.

Read 1: A + LF
Read 2: B, no LF
Read 3: empty result signalling end for this text-reader interface

Distinguish an empty line from no returned data

A physical blank line contains a newline character. After stripping, it can become an empty string like a mistaken EOF sentinel. Test a blank line between records and one final incomplete record under both permissive and strict termination policies.

References

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