Writing a Final Newline Deliberately

A record writer needs to decide whether every record ends with a newline or whether newlines only separate adjacent records.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compare two results
  2. Test the empty and singleton cases
  3. Compare byte sequences for empty and nonempty outputs
  4. Keep physical lines and escaped internal breaks separate

Compare two results

Writing two lines by joining them with a newline puts a boundary between them and no final one. Writing each line with a terminator produces an extra final separator byte sequence. Joining text fragments explains this placement rule.

Test the empty and singleton cases

A single record may need a trailing newline even though no join separator is produced. An empty export can remain empty if no header is required. Physical line endings define the expected bytes.[1]

Compare byte sequences for empty and nonempty outputs

Writing the two records A and B with a newline after each yields A\nB\n. Joining just between lines yields A\nB. A reader can allow both, while a format or comparison contract might require the final terminator. See line-ending representations.

No records → decide empty bytes under ordinary line writing
One record A → A plus the chosen terminator
Two records A and B → one terminator after each if required

Keep physical lines and escaped internal breaks separate

If a value contains a line break, serialization may need quoting or escaping. Appending a final terminator still concerns record framing. Test one literal line break field and an ordinary two-record file.

References

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