Skip to content

Atomic Replacement - Editing Files Safely ​

update/delete are operations that change part of a file's contents. But if the program shuts down while writing, the file can get corrupted.

The safe way (temporary file + replace):

python
import os, tempfile

def rewrite_file(path: str, lines: list[str]) -> None:
    """A function that safely rewrites a file (atomic replacement)"""
    tmp_path = path + ".tmp"          # 1. write the finished version to a temp file first
    with open(tmp_path, "w", encoding="utf-8") as f:
        f.writelines(lines)
    os.replace(tmp_path, path)        # 2. once finished, swap it with the original 'in an instant'

os.replace swaps the file in one step at the file system level, so the original stays safe even if the program shuts down midway. (Requirement: update/delete must consider stability, e.g. "full rewrite / temporary file / atomic replacement (recommended)")

Summary ​

ConceptSummary
Atomic replacementFinish the draft, then swap it in all at once

Source: Codyssey-B1/B2-1