brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: os.replace swaps in a new file in one step, on every platform

Scripting
~/tips/tip-scripting-os-replace-atomic

import json, os, tempfile

Write a file safely by writing a temp copy first and then replacing the original.

A script that writes state.json directly and crashes halfway leaves a broken file behind. Writing to a temp file in the same folder and then swapping it in avoids that.

os.replace renames a file and overwrites the target if it exists:

import json, os, tempfile

def save(path, data):
    folder = os.path.dirname(os.path.abspath(path))
    fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
    with os.fdopen(fd, "w") as f:
        json.dump(data, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)

On POSIX systems the rename is atomic, so a reader sees the old file or the new file, never half of one. The fsync makes sure the data is on disk before the swap.

I’d use os.replace instead of os.rename because rename refuses to overwrite an existing file on Windows, while replace does it everywhere.

The temp file must be on the same filesystem as the target, which is why the example creates it in the same folder. Across filesystems the call fails instead of copying. Also, mkstemp gives the new file private permissions, so if other users need to read it, set the mode with os.chmod before the replace. And if the write raises, remove the temp file, or it stays behind.

Further reading: os.replace, tempfile.mkstemp

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest from collections import Counter import shutil from contextlib import chdir All Scripting tips (10) All topics

Link