IC Improve Code Recipes

Recipe 10.2 · Python

Atomic File Writes

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

A job writes an output file. Another process, or a person, reads it while it is half written and gets a truncated file. Or the job crashes in the middle, and the old good file has already been overwritten with half a new one. Both happen most often with exactly the files that matter: extracts for downstream systems, configuration and state files.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The file exists, with partial content, from the first line until the last. A reader polling the folder sees it immediately.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Write an output file directly in place, row by row (p208_r10_2_write_file_in_place_before.py)
"""Write an output file directly in place, row by row

Source: ImproveCode, Chapter 10, Recipe 10.2 "Atomic File Writes"
Section: The way it's often written
Book page: 208  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
StreamWriter(path, append=false) -> open(path, "w"); a crash mid-loop leaves a
truncated file that readers can see.
"""

from collections.abc import Callable, Iterable
from typing import Any


def write_rows(output_path: str, rows: Iterable[Any],
               format_row: Callable[[Any], str]) -> None:
    with open(output_path, "w") as writer:
        for row in rows:
            writer.write(format_row(row) + "\n")

The improved recipe

Write to a temporary file in the same folder, flush it to disk, then rename it over the target. A rename within one volume is atomic: readers see either the old file or the complete new one, never a mixture.

A usage snippet that streams rows straight into the temporary file:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Atomic file write: write to a temp file, fsync, then rename over the target (p208_r10_2_atomic_file_write_temp_rename.py)
"""Atomic file write: write to a temp file, fsync, then rename over the target

Source: ImproveCode, Chapter 10, Recipe 10.2 "Atomic File Writes"
Section: The improved recipe
Book page: 208-210  -- original C# listing
Converted from C# to Python.
FileStream/File.Move(overwrite) -> open(mode "xb") + os.fsync + os.replace.
The async callback runs on the event loop; blocking file writes are kept simple
(use aiofiles or asyncio.to_thread for heavy writers). CancellationToken is
replaced by asyncio task cancellation.
"""

from __future__ import annotations

import os
import uuid
from collections.abc import Awaitable, Callable
from typing import BinaryIO


async def write_async(
    path: str,
    write: Callable[[BinaryIO], Awaitable[None]],
) -> None:
    if not path or not path.strip():
        raise ValueError("path must not be null or whitespace")
    if write is None:
        raise ValueError("write must not be None")

    target = os.path.abspath(path)
    folder = os.path.dirname(target)
    os.makedirs(folder, exist_ok=True)
    temp = os.path.join(
        folder, f".{os.path.basename(target)}.{uuid.uuid4().hex}.tmp")

    try:
        # "xb" == FileMode.CreateNew, write-only.
        with open(temp, "xb") as stream:
            await write(stream)
            stream.flush()
            os.fsync(stream.fileno())  # Flush(flushToDisk: true)
        os.replace(temp, target)      # File.Move(..., overwrite: true)
    except BaseException:
        try:
            os.remove(temp)
        except FileNotFoundError:
            pass
        raise


async def write_all_text_async(
    path: str,
    contents: str,
    encoding: str = "utf-8",  # UTF8Encoding(false): no BOM
) -> None:
    if contents is None:
        raise ValueError("contents must not be None")

    async def _write(stream: BinaryIO) -> None:
        stream.write(contents.encode(encoding))

    await write_async(path, _write)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Usage: stream repository rows into a CSV file atomically (p210_r10_2_atomic_csv_export_usage.py)
"""Usage: stream repository rows into a CSV file atomically

Source: ImproveCode, Chapter 10, Recipe 10.2 "Atomic File Writes"
Section: The improved recipe
Book page: 210  -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; `repository.stream_async()` is an async
iterator (await foreach) and AtomicFile is the write_async helper from p208.
StreamWriter over the stream -> io.TextIOWrapper.
"""

from __future__ import annotations

import io
from typing import Any, BinaryIO

from p208_r10_2_atomic_file_write_temp_rename import write_async


async def export_customers(repository: Any) -> None:
    async def _write(stream: BinaryIO) -> None:
        writer = io.TextIOWrapper(stream, encoding="utf-8", newline="")
        try:
            async for row in repository.stream_async():
                writer.write(row.to_csv_line() + "\r\n")
            writer.flush()
        finally:
            writer.detach()  # leave the underlying stream open for fsync

    await write_async(r"D:\exports\customers.csv", _write)

How it works

The temporary file sits in the same folder as the target, so it is on the same volume, which is what makes the rename atomic. Its name starts with a dot and ends with .tmp, so watchers and pickup jobs can be told to ignore it (Recipe 10.3), and it includes a GUID so two writers never collide on the temp name.

FileMode.CreateNew fails if the temp file somehow exists, rather than appending to junk. After the caller's delegate finishes, the stream is flushed twice: FlushAsync pushes .NET's buffer to the operating system, and Flush(flushToDisk: true) asks the operating system to push its cache to the disk. Without the second step, a power cut shortly after the rename can leave a correctly named file full of zeros on some file systems.

File.Move with overwrite: true replaces the target in one operation, using MoveFileEx with replace on Windows and rename on Linux. If anything fails before that, the catch deletes the temp file and rethrows, and the old target is untouched. File.Delete does not throw when the file is already gone.

WriteAllTextAsync covers the common case and defaults to UTF-8 without a byte order mark. Chapter 11 explains when a downstream reader, usually Excel, needs the mark.

Variations and pitfalls

  • Keep a backup. File.Replace(temp, target, backupPath) swaps the files and keeps the previous version, which is useful for configuration files. It requires the target to exist already.
  • Readers must cooperate. Atomic writes stop readers seeing partial files. They do not stop a reader holding the old file open, which on Windows makes the move fail with a sharing violation. Retry briefly, as the watcher in the next recipe does.
  • Signal files. If a downstream system wants a .done file, write the data file atomically first, then the signal file.