CertGrid CertGrid
Hands-on Lab·Python Automation for IT

Python Encodings, Temp Files and Atomic Writes

Two problems that only show up in production. The first is encoding: `read_text()` uses whatever the locale says, which is not necessarily what wrote the file. The second is worse - a script that fails half way through a write leaves a truncated file where the good one used to be. This guide shows both, and the function that makes the second impossible.

Files and Data Formats Guide 15 of 39 Intermediate

Written against the versions above. **PEP 540** means the C locale now enables UTF-8 mode rather than degrading to ASCII, which this guide measures - so the classic locale failure is largely gone. `unlink(missing_ok=True)` needs **3.8**, and `os.replace` has been the portable rename since 3.3.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 GB

Before you start

  1. Which encoding a text file is read with

  2. And what the same bytes decode to

  3. errors=, for data you do not control

  4. A temporary file that cleans itself up

  5. The write that leaves a half-file behind

  6. The atomic version

  7. And on a run that succeeds

  8. Why os.replace and not os.rename

Official sources