File Modes for Reading, Writing, and Appending
A file open mode determines which operations are permitted and whether an existing file is preserved, truncated, or extended.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Check before opening
In Python, write mode truncates an existing file when opened successfully. Append mode preserves earlier content and directs appended writes to the end. The observable effect can therefore occur before a newly generated report is fully ready.
Use a test fixture
Create a temporary file containing old data, run the intended operation, and inspect the content afterward. A write test should specify whether the old data survives. Fresh fixtures keep this check independent of real files.[1]
Predict which byte contents survive opening
If a report contains A, opening in ordinary write mode truncates the report before any new content is written. Opening in append mode and writing B yields AB for this simple example. Read mode retrieves existing data without intentionally adding content. See read-only input handles.
Initially file contains A
Open write then close without writing → empty
From original A, open append then write B → AB
From original A, read → A
Test failure before the first write
A producer can fail after truncating a destination but before generating its replacement. Stage output separately when readers require a complete old or new version. Decide whether an append-only format also requires explicit record boundaries and durability.