Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 33 / 101

Finish the write before the swap.

Reduce the risk of leaving a half-written configuration file behind.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

Writing directly over an important file can leave partial content if the process fails. A common pattern writes a complete replacement to a temporary file in the same directory, closes it, then replaces the target path. On supported local filesystems the rename-style replacement is atomic with respect to observers: they see the old file or the new file, not half the new content.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

safe_file_writes.py
from pathlib import Path
import json, os, tempfile
folder = Path("config")
folder.mkdir(exist_ok=True)
target = folder / "settings.json"
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=folder, delete=False) as stream:
    temp = Path(stream.name)
    json.dump({"retries": 3}, stream)
try:
    os.replace(temp, target)
finally:
    temp.unlink(missing_ok=True)
print(json.loads(target.read_text(encoding="utf-8"))["retries"])
↳ EXPECTED OUTPUT
3

03 Under the hood

  1. 1

    The temporary file lives beside the target to keep both paths on the same filesystem. It is closed before replacement, which matters on Windows.

  2. 2

    os.replace replaces the destination when allowed. The finally block removes any leftover temporary path if replacement failed.

  3. 3

    Atomic visibility is not identical to durable storage after power loss. Higher-assurance storage may need fsync on the file and directory, tested filesystem guarantees, and a backup strategy.

04 Your turn, builder

A SMALL MISSION

Write a new note to a temporary sibling path, replace the target, and confirm the content.

Reveal one possible solution +
one_possible_solution.py
from pathlib import Path
import os
folder = Path("practice")
folder.mkdir(exist_ok=True)
temp, target = folder / "note.tmp", folder / "note.txt"
temp.write_text("New version", encoding="utf-8")
os.replace(temp, target)
print(target.read_text(encoding="utf-8"))

05 Check your signal

QUICK SIGNAL CHECK

Why create the temporary file in the target directory?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.