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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "manifest.json"
    path.write_text('{"version": 1}\n', encoding="utf-8")
    try:
        with path.open("w", encoding="utf-8") as stream:
            stream.write(json.dumps({"asset": object()}))
    except TypeError:
        print(repr(path.read_text(encoding="utf-8")))
# ''

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import json
import os
from pathlib import Path
from tempfile import NamedTemporaryFile


def write_json_atomic(path, value):
    """Replace a small JSON file; its parent directory must already exist."""
    target = Path(path).absolute()
    payload = (json.dumps(value, ensure_ascii=False, allow_nan=False,
                          indent=2) + "\n").encode("utf-8")
    temporary = None
    try:
        with NamedTemporaryFile(
            mode="wb", dir=target.parent,
            prefix=f".{target.name}.", suffix=".tmp", delete=False,
        ) as stream:
            temporary = Path(stream.name)
            stream.write(payload)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, target)
        temporary = None
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import json
from pathlib import Path
from tempfile import TemporaryDirectory

from atomic_json import write_json_atomic

with TemporaryDirectory() as directory:
    path = Path(directory) / "manifest.json"
    write_json_atomic(path, {"version": 1, "bundle": "base.zip"})
    write_json_atomic(path, {"version": 2, "bundle": "bonus.zip"})
    print(json.loads(path.read_text(encoding="utf-8")))
    print(sorted(item.name for item in Path(directory).iterdir()))
# {'version': 2, 'bundle': 'bonus.zip'}
# ['manifest.json']

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch

from atomic_json import write_json_atomic


class AtomicJsonTests(unittest.TestCase):
    def setUp(self):
        self.directory = TemporaryDirectory()
        self.addCleanup(self.directory.cleanup)
        self.root = Path(self.directory.name)
        self.path = self.root / "manifest.json"
        self.old = b'{"version": 1}\n'
        self.path.write_bytes(self.old)

    def assert_preserved(self):
        self.assertEqual(self.path.read_bytes(), self.old)
        self.assertEqual(set(self.root.iterdir()), {self.path})

    def test_create_and_replace(self):
        value = {"version": 2, "label": "caf\u00e9 \U0001f680"}
        write_json_atomic(self.path, value)
        self.assertEqual(json.loads(self.path.read_bytes()), value)
        fresh = self.root / "fresh.json"
        write_json_atomic(fresh, [])
        self.assertEqual(fresh.read_bytes(), b"[]\n")
        self.assertEqual(set(self.root.iterdir()), {self.path, fresh})

    def test_serialization_failure_preserves_old_file(self):
        for value in ({"bad": object()}, {"bad": float("nan")}):
            with self.assertRaises((TypeError, ValueError)):
                write_json_atomic(self.path, value)
            self.assert_preserved()

    def test_sync_failure_preserves_old_file(self):
        with patch("atomic_json.os.fsync", side_effect=OSError("sync failed")):
            with self.assertRaises(OSError):
                write_json_atomic(self.path, {"version": 2})
        self.assert_preserved()

    def test_replace_failure_preserves_old_file(self):
        with patch("atomic_json.os.replace",
                   side_effect=PermissionError("replace denied")):
            with self.assertRaises(PermissionError):
                write_json_atomic(self.path, {"version": 2})
        self.assert_preserved()


if __name__ == "__main__":
    unittest.main()

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.