Write JSON Files Atomically in Python with os.replace
A game asset pipeline stores its latest successful bundle in manifest.json. Opening that file for writing immediately truncates the previous manifest. A serialization error or interrupted write can leave the next build with an empty or incomplete document.
Prepare the new JSON separately, write it to a neighboring temporary file, and replace the destination only after that file is ready. This Python 3.8 or later recipe targets small documents, an application-controlled directory, and one writer. It does not require a third-party package.
Reproduce the Truncation Problem
This example uses a disposable directory so the original file is only a fixture:
| |
The unsupported object() prevents serialization, but opening with w has already destroyed the old contents. Serializing before opening fixes this particular failure; writing the resulting text directly to the destination still leaves a window for a partial write.
Treat the destination name as the publication point. Until the replacement succeeds, readers should continue to find the previous complete document.
Write a Neighboring File Before Replacing
Save this as atomic_json.py:
| |
The helper encodes the entire document before creating any file. The
JSON encoder documentation
explains allow_nan=False: it rejects non-finite floats instead of writing NaN or Infinity. This choice is separate from application schema validation; validate your manifest’s fields before calling the helper.
NamedTemporaryFile
supplies a unique name. Its explicit dir keeps staging beside the destination, and delete=False leaves the name available after close. Avoid a shared fixed name such as manifest.json.tmp, which can collide with another invocation or a leftover file.
The staging handle closes before replacement, which also avoids replacing an open staging file on Windows. The finally block removes staging files after ordinary failures. If cleanup itself fails, that error also reaches the caller.
Use the Replacement as the Commit Point
Run this beside the module:
| |
os.replace
replaces an existing destination file when permitted. Keeping both paths on the same filesystem avoids a cross-filesystem move. On filesystems that provide atomic replacement, opening the destination sees the old complete document or the new complete document, without a partially written destination between them.
Let exceptions stop the publishing step. A permission problem, missing parent directory, or Windows sharing restriction should produce a failed save. Deleting the destination and retrying as a normal write would defeat the preservation policy.
Test Success and Failures Before Commit
Save this as test_atomic_json.py, then run it with your Python 3 interpreter:
| |
These checks exercise real temporary files and replacement. Injected sync and replacement failures make the failure paths repeatable without filling a disk or changing directory permissions. They verify both exact preservation of the old bytes and removal of the unused staging file.
They do not simulate a power failure. Test the actual storage environment separately if crash recovery is a requirement.
Separate Atomic Visibility from Durability
flush() and
os.fsync
request that staged data reach storage before replacement. This helper does not sync the containing directory after renaming and does not promise recovery of the new name after a power loss. Validate stronger durability requirements against the operating system and filesystem.
Replacement also installs a new file’s metadata; it does not preserve the old file’s permissions, ownership, ACLs, or hard-link relationships. Use this recipe for an application-owned regular file, not a symlink-based configuration scheme. An abruptly terminated process can leave a staging file behind, even though ordinary exceptions trigger cleanup.
Atomic replacement is not a lock or a transaction across several files. Two writers can each prepare a complete document and overwrite one another’s changes. Keep one writer for this recipe; use explicit coordination or a transactional store when updates must merge. Because serialization is held in memory, choose a different staging strategy for very large exports.