Python Atomic File Writes: Safely Replace JSON with os.replace
Write JSON through a temporary file and os.replace. Test failure cleanup, understand open readers, and separate atomic replacement from crash durability and locking.
To replace a local JSON file without exposing a partially written destination, prepare a temporary file in the destination directory, finish and close it, then call os.replace. Keep the old destination until that replacement succeeds. This guide includes a tested Python example and explains the separate problems of persistence after power loss, metadata, open readers and competing writers.
The failure starts when you open the destination too early
A small configuration writer often opens settings.json in write mode and calls json.dump. Opening an existing file in that mode truncates it before serialization finishes. If serialization raises, the process exits or storage fails partway through, the previous usable configuration is already gone. A later reader can encounter an empty file or incomplete JSON.
The alternative is to stage a complete replacement under another name. A successful atomic rename changes which file the destination pathname identifies without an intermediate state where that name identifies a half-written staging file. The old and new files still have separate identities; the operation does not edit every existing reference to the old file.
This tutorial targets a trusted local directory controlled by the application. It does not accept arbitrary public upload destinations or defend against a hostile process changing parent-directory links. The example is deliberately a single-file writer, suitable for understanding the boundary before adapting it to an application.
Stage, flush, close, replace
First serialize the complete value and encode it as UTF-8 before creating the staging file. This catches unsupported values, disallowed non-finite numbers and encoding failures without touching the destination. The example keeps the serialized bytes in memory, which is convenient for modest configuration files; it is not a streaming solution for arbitrarily large datasets.
Create the staging file with tempfile.mkstemp in the destination’s parent directory. Explicit placement avoids relying on the operating system’s default temporary directory, which could be on another filesystem. The temporary name is unique, and the returned descriptor belongs to the caller until it is closed or transferred to a file object.
Write the bytes, flush Python’s buffered stream, request fsync on its descriptor, and close the stream. Only then replace the destination. The finally block removes a remaining staging pathname after an ordinary exception; following a successful replace that temporary name has already been consumed.
Do not delete the destination before replacement. Doing so adds a missing-file interval and sacrifices the previous version even if the subsequent rename fails. Do not use a fixed staging name shared by every writer either: separate attempts should not overwrite one another’s unfinished files.
Source: Python tempfile: secure creation, placement and manual cleanup ↗
What os.replace promises, and what it does not
Python documents replacement of an existing file when permissions allow it, possible failure across filesystems, and atomicity of a successful rename. That is why the example stages beside the target and uses os.replace rather than assuming every platform’s os.rename will overwrite an existing destination in the same way.
Atomicity concerns the pathname switch. It does not guarantee that every reader now uses the new bytes, that a multi-file configuration changes as one unit, or that a read-modify-write sequence is isolated. Keep those requirements explicit rather than expanding the word atomic to cover all of them.
A failed attempt must still be reported. Permission problems, a nonempty directory at the target, or an unsupported filesystem behavior are not reasons to silently fall back to copying bytes over the live file. That fallback would change the failure guarantee the caller expects.
| Requirement | What this example provides | What requires more work |
|---|---|---|
| Avoid a partially written destination | Stage fully, then replace once | Validate backend/filesystem behavior |
| Handle ordinary pre-replace errors | Keep destination and clean staging file | Cleanup errors and abrupt termination policy |
| Survive a power failure | Flush and fsync the staging file | Directory persistence and platform-specific guarantees |
| Prevent lost updates | No writer isolation | Locking or transactional storage |
| Preserve ownership and permissions | No metadata copying | Explicit metadata policy |
A complete runnable lab with failure checks
Save this script as atomic_write.py and run python atomic_write.py. It uses only Python’s standard library. The exact published script passed 35 checks on Python 3.12.14 in a POSIX environment. All files are invented fixtures inside a TemporaryDirectory, so the lab does not modify an application configuration.
The wrapper intentionally uses allow_nan=False and explicit UTF-8. Those choices reject NaN, Infinity and unencodable strings before staging. They do not validate an application schema. Use the related JSON parsing guide for separate questions about duplicate keys and nonstandard numeric values.
Two error paths inject OSError at fsync and replace using unittest.mock. This tests error propagation, target preservation and cleanup at those boundaries. It does not reproduce a real disk-full event, a kernel crash or a power interruption. The directory-target case exercises an actual rejected replacement.
"""Python 3.12+; trusted local directory; no crash-durability claim."""
import json
import os
from pathlib import Path
import platform
import tempfile
from unittest.mock import patch
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def atomic_json(path, value):
# Serialize and encode before creating any temporary file.
data = (json.dumps(value, ensure_ascii=False, allow_nan=False) + '\n').encode('utf-8')
target = Path(os.path.abspath(os.fspath(path)))
fd, name = tempfile.mkstemp(dir=target.parent, prefix='.' + target.name + '.', suffix='.tmp')
temp = Path(name)
try:
stream = os.fdopen(fd, 'wb')
fd = None # stream now owns the descriptor
with stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
# Close before replacing. Do not unlink the destination first.
os.replace(temp, target)
finally:
if fd is not None:
os.close(fd)
# Successful replace consumed the temporary pathname.
temp.unlink(missing_ok=True)
def main():
with tempfile.TemporaryDirectory() as name:
root = Path(name)
target = root / 'settings.json'
old = {'revision': 1, 'label': 'old'}
new = {'revision': 2, 'label': 'café'}
atomic_json(target, old)
check(json.loads(target.read_text()) == old, 'create missing target')
check(not list(root.glob('.*.tmp')), 'no staging files after create')
real_replace = os.replace
def inspect_replace(src, dst):
check(Path(src).parent == target.parent, 'staged in target directory')
check(json.loads(target.read_text()) == old, 'old content before replacement')
check(json.loads(Path(src).read_text()) == new, 'complete new content staged')
return real_replace(src, dst)
with patch.object(os, 'replace', side_effect=inspect_replace):
atomic_json(target, new)
check(json.loads(target.read_text()) == new, 'new content after replacement')
check(b'caf\xc3\xa9' in target.read_bytes(), 'explicit UTF-8 bytes')
check(target.read_bytes().endswith(b'\n'), 'final newline')
check(not list(root.glob('.*.tmp')), 'no staging files after replacement')
for value in [object(), {'x': float('nan')}, {'x': float('inf')}, {'x': '\ud800'}]:
before = target.read_bytes()
try:
atomic_json(target, value)
except (TypeError, ValueError, UnicodeEncodeError):
check(True, 'serialization or encoding failure raised')
else:
raise AssertionError('Expected serialization failure')
check(target.read_bytes() == before, 'serialization failure preserves target')
check(not list(root.glob('.*.tmp')), 'serialization leaves no staging file')
# Inject exceptions; these do not simulate real disk-full or power loss.
for operation in ['fsync', 'replace']:
before = target.read_bytes()
with patch.object(os, operation, side_effect=OSError('injected ' + operation)):
try:
atomic_json(target, {'revision': 3})
except OSError:
check(True, operation + ' error propagated')
else:
raise AssertionError('Expected injected failure')
check(target.read_bytes() == before, operation + ' failure preserves target')
check(not list(root.glob('.*.tmp')), operation + ' failure cleans staging file')
directory = root / 'directory-target'
directory.mkdir()
(directory / 'keep.txt').write_text('keep')
try:
atomic_json(directory, new)
except OSError:
check(True, 'nonempty directory cannot be replaced by this file')
else:
raise AssertionError('Expected directory replacement failure')
check((directory / 'keep.txt').read_text() == 'keep', 'directory contents preserved')
check(not list(root.glob('.*.tmp')), 'directory failure cleans staging file')
if os.name == 'posix':
atomic_json(target, old)
alias = root / 'old-link.json'
os.link(target, alias)
with target.open('rb') as reader:
atomic_json(target, new)
check(json.loads(reader.read()) == old, 'already-open reader retains old file')
check(json.loads(target.read_text()) == new, 'new open sees replacement')
check(json.loads(alias.read_text()) == old, 'hard link retains old file')
# Two writers both read revision 2, then each writes revision 3.
snapshot_a = json.loads(target.read_text())
snapshot_b = json.loads(target.read_text())
snapshot_a['revision'] += 1
snapshot_b['revision'] += 1
atomic_json(target, snapshot_a)
atomic_json(target, snapshot_b)
check(json.loads(target.read_text())['revision'] == 3, 'replacement is not increment transaction')
check(not list(root.glob('.*.tmp')), 'final staging cleanup')
print(f'PASS: {checks} checks; Python {platform.python_version()}; {os.name}')
if __name__ == '__main__':
main()
Read the test results as specific evidence
The expected final line is PASS: 35 checks; Python 3.12.14; posix in the authoring environment. Another Python patch version changes that version text. Three open-reader and hard-link checks run only when os.name is posix, so a non-POSIX execution has a different check count and is not evidence of the same platform behavior.
The replacement inspection observes the old JSON at the destination while the complete new JSON exists in a neighboring file. After the real replacement, a fresh read returns the new object. This demonstrates the intended ordering in an ordinary successful operation; it is not a stress test proving every possible reader interleaving.
Serialization failures preserve the previous byte sequence and leave no staging file. The injected fsync and replacement failures do the same. These are useful regression cases because a careless refactor can move destination truncation earlier, omit cleanup, or replace a file before all required preparation succeeds.
The final scenario deliberately models a lost update without threads. Two writers read revision 2, each computes revision 3, then both publish. The result is revision 3 rather than 4. Each file replacement can be atomic while the logical increment is still incorrect.
Atomic visibility is separate from crash durability
flush moves buffered Python data toward the operating system; fsync requests synchronization of the file. The example performs both before replacement. That ordering is useful, but a file’s synchronized data and the persistence of a changed directory entry are separate concerns.
Linux’s fsync documentation states that synchronizing a file does not necessarily synchronize its directory entry; explicitly synchronizing the directory is needed for that. A Linux-specific durable replacement protocol therefore needs to consider the containing directory after rename as well as the staged file before it.
This lab does not implement or certify that larger protocol. Filesystem, mount, storage and platform behavior matter, and fault-injection checks in a Python process cannot establish survival of real power loss. If that requirement is central, use a documented platform-specific implementation and test the actual storage environment.
An error after a replacement has succeeded also needs different reporting from an error before it. For example, failure to synchronize a directory afterward does not imply the old pathname mapping was restored. A caller should not blindly retry a non-idempotent update on the assumption that nothing changed.
Source: Linux fsync manual: file and directory synchronization ↗
Already-open readers and metadata follow file identity
On the POSIX lab host, a reader opened before replacement continues to read the old file. A new open through settings.json reads the replacement. The hard-link fixture also retains the old content under another name. Linux rename documentation describes the persistence of open file descriptors and other hard links.
This matters for applications that keep configuration handles open indefinitely. Replacing the pathname does not force those readers to reopen it. Define a reload policy and check how the consuming process notices changes. On Windows, sharing modes and open handles can affect replacement; this lab makes no Windows compatibility claim.
The replacement file comes from mkstemp rather than being the original file with new contents. Do not assume the old permission bits, owner, ACLs, extended attributes or other metadata are preserved. mkstemp uses restrictive creation permissions; decide what the final file needs and set any required metadata before publishing it.
If destination paths may be symbolic links, decide whether the application intends to replace a directory entry or modify a linked target. Those are different operations. Do not add automatic path resolution as an unnoticed behavior change. The example assumes application-controlled paths and does not test adversarial symlink races.
Source: Linux rename manual: replacement, open descriptors and hard links ↗
Choose the next check from the observed failure
If replacement raises an error indicating a cross-device operation, inspect where staging actually occurs. A temporary directory chosen globally may live on another mount. Keep staging in the destination parent and investigate the error rather than implementing a copy-and-delete fallback that exposes partial data.
If the next reader reports permission denied, inspect the new file’s metadata and the parent directory’s access policy. A successful write by one account does not establish readability by a different service account. Test the consuming identity as part of deployment; do not broadly relax permissions just to make the symptom disappear.
If valid complete files overwrite one another’s changes, investigate writer coordination. Protect the complete read-compute-write operation with an appropriate interprocess protocol, or move shared updates into transactional storage. Locking only the final replace leaves the stale-read problem intact.
If staging files remain after an abrupt process stop, treat cleanup as a separate recovery task. The finally block runs for normal exception unwinding, not every termination mode. A cleanup job must distinguish its own abandoned attempts from files still in use; deleting every matching temporary name during startup is unsafe when another writer may be active.
Publish a prepared file and keep the limits visible
For a small application-owned JSON file, the essential sequence is straightforward: serialize, stage beside the target, finish and close the file, then replace the destination once. This keeps ordinary preparation failures away from the last known usable destination and gives you clear checkpoints to test.
Before adopting the function, decide who can write, who must read, whether old handles need reloading, and whether power-loss persistence is required. Those decisions determine the additional metadata, coordination and storage work. A single-file replacement is a useful building block when its contract stays precise.
Your next steps
- Stage in the destination directory and keep the old destination until os.replace succeeds.
- Serialize and encode before staging; flush, fsync and close before replacement.
- Atomic replacement does not isolate a read-modify-write operation.
- Open readers and hard links can retain the old file on POSIX systems.
- Metadata preservation and crash durability need explicit platform-specific policies.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →