Trending

World technology news

→
A completed JSON file replaces the previous report in one operation.
Software Engineering · 2026
Software Engineering

Write a JSON report with atomic replacement in Python

Finish a JSON report in the destination directory and test that a failed write leaves the last complete report readable.

Developer's JournalPublished: Nov 30, 20266 min read
Reading progress0%
In this article
  1. What readers see during an export
  2. Create the temporary file beside the destination
  3. Encode, flush, close and replace
  4. Check that a failed write preserves the old report
  5. Account for power loss and open readers
  6. Use a single writer or define what wins

What readers see during an export

A shop exports its daily sales report as JSON at closing time. A support screen opens the report at the same path each time. Opening that path in write mode truncates the old contents immediately. A reader that arrives during the export can see an empty file or a partially written object. If serialization fails, the incomplete file can still be there the next morning. This example writes the complete new report beside the destination. After writing, flushing and closing that file, it replaces the destination in a single call. The existing report stays available until the changeover. This is useful for a small, self-contained export. The example exercises creation, replacement and serialization failure using sample records and the city name İzmir. It needs no external service or production data.

Create the temporary file beside the destination

NamedTemporaryFile creates a file with a randomly generated component in its name. Set dir to the destination parent so the location does not depend on the operating system’s default temporary directory. A general temporary directory can sit on a different filesystem, and os.replace can fail across filesystems. Readers should open report.json directly or select completed filenames only. The example retains the temporary name after closing because the replacement call still needs that path. A context manager closes the handle before replacement, which also avoids a problem with holding the source file open on Windows. Prepare the destination directory before starting the export. Check access with the service account that performs the replacement and the account that reads the finished report.

Application flowConceptual sketch · summary of the article's technical flow

Encode, flush, close and replace

The JSON encoder writes into the temporary file. Explicit UTF-8 keeps Turkish characters independent of the machine’s default encoding. ensure_ascii=False keeps them legible in the file, and allow_nan=False rejects a value outside standard JSON. Once json.dump returns, data may still be buffered by Python. Call flush before fsync so the operating system can synchronize the data already handed to it. The context manager then closes the file, and os.replace uses its path to replace the destination if permissions permit. The Python documentation describes the operation as atomic if successful. A reader already holding the old file open can continue to see the old file. A reader waiting for the new report should reopen the destination path.

Check that a failed write preserves the old report

Run the example with Python 3.12. The first call creates a report for day one. The next call replaces it with day two. The example decodes the new file, checks its contents and verifies that the UTF-8 bytes for İzmir were written. The third call passes NaN in a total field and triggers a serialization error. The encoder may already have written part of the object to the temporary file. The finally block removes it, and the destination still contains the exact bytes from day two. The sample also checks that the directory contains report.json alone. This test gives the operations team a reproducible way to verify that a bad report leaves the last complete report readable.

import json
import os
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory


def replace_json(destination: Path, data: object) -> None:
    temporary_path = None
    try:
        with NamedTemporaryFile(
            mode="w", encoding="utf-8", newline="\n", dir=destination.parent,
            prefix=f".{destination.name}.", suffix=".tmp", delete=False,
        ) as temporary:
            temporary_path = Path(temporary.name)
            json.dump(data, temporary, ensure_ascii=False, allow_nan=False)
            temporary.write("\n")
            temporary.flush()
            os.fsync(temporary.fileno())
        os.replace(temporary_path, destination)
    finally:
        if temporary_path is not None:
            temporary_path.unlink(missing_ok=True)


if __name__ == "__main__":
    with TemporaryDirectory() as directory:
        report = Path(directory) / "report.json"
        replace_json(report, {"day": 1, "city": "İzmir"})
        assert json.loads(report.read_text(encoding="utf-8"))["day"] == 1
        replace_json(report, {"day": 2, "city": "İzmir"})
        original = report.read_bytes()
        assert json.loads(original) == {"day": 2, "city": "İzmir"}
        assert "İzmir".encode("utf-8") in original

        try:
            replace_json(report, {"day": 3, "total": float("nan")})
        except ValueError:
            pass
        else:
            raise AssertionError("Expected strict JSON serialization to fail")

        assert report.read_bytes() == original
        assert list(report.parent.iterdir()) == [report]
        print("report.json contains day 2; no temporary file remains")

Account for power loss and open readers

Synchronizing file content and making the updated directory entry durable through a power loss are separate concerns. The portable example does not perform a parent directory synchronization. For a stronger durability requirement, verify what the filesystem, operating system and backup arrangement actually guarantee. This local run exercises ordinary execution and a controlled error. It does not simulate a power cut or a network filesystem cache. On Windows another process can also hold the destination open in a mode that prevents replacement. Report that error and consider a bounded retry only when it is known to be transient. Check file permissions after replacement in the environment where the result will be read because the replacement file is a newly created file.

Use a single writer or define what wins

Two exporters can create separate temporary files and replace the same destination. The last successful replacement determines which report a new reader sees. A report that accumulates updates from multiple jobs needs a different coordination decision. You can run a single export job, assign different filenames to different versions or manage revisions in a database. The code here assumes each exporter generates a complete report. Record the production day or batch identifier inside the document so a retained file can be recognized after an export fails. Log when a replacement succeeded, which stage failed and the size of the completed report. Run a controlled failure before deploying the workflow and make sure the reader can still show the last successful report.

1 reads ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.