Sub topic 13
Writing files safely with a temporary file
This chapter assumes you know how to open files with with, write text with an explicit encoding, build paths with pathlib, and catch exceptions with try/except. It covers one problem: a program that crashes while writing can leave a file half-written.
The problem with writing in place
Opening an existing file with "w" truncates it to zero bytes immediately. If the program crashes, the disk fills up, or the power fails before the write finishes, the old content is gone and the new content is incomplete. A reader that opens the file at that moment also sees a partial result.
This matters for files that other code depends on, such as configuration, saved state, and indexes. It matters less for throwaway output.
The pattern: write elsewhere, then swap
The fix has three steps:
- Write the new content to a temporary file in the same directory as the target.
- Flush the content to disk.
- Replace the target with the temporary file in one step.
os.replace performs the swap. On the same filesystem it is atomic on both POSIX systems and Windows. Any reader sees either the complete old file or the complete new file, never a mix.
The function
import os
import tempfile
from pathlib import Path
def atomic_write_text(path, text, encoding="utf-8"):
path = Path(path)
fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding=encoding) as tmp:
tmp.write(text)
tmp.flush()
os.fsync(tmp.fileno())
os.replace(tmp_name, path)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raise
atomic_write_text("settings.txt", "theme=dark\n")
print(Path("settings.txt").read_text(encoding="utf-8"))Each part has a job:
tempfile.mkstemp(dir=path.parent)creates a uniquely named file and returns an open low-level file descriptorfdand its name. Thedirargument keeps the temporary file on the same filesystem as the target.os.replaceis only atomic within one filesystem, and across filesystems it fails.os.fdopen(fd, "w", encoding=encoding)wraps the descriptor in a normal text file object, so you get the usualwritemethod and encoding handling.flush()moves Python's buffer to the operating system.os.fsync()asks the operating system to write its own cache to the disk. Without both, a power failure shortly afteros.replacecould leave an empty or partial file.except BaseExceptionremoves the temporary file on any failure, includingKeyboardInterrupt, and then re-raises the error.missing_ok=Trueavoids a second error if the file is already gone.
If atomic_write_text raises, the original settings.txt is unchanged.
Gotchas
- Same directory. Do not put the temporary file in
/tmpunless the target is also there. A different filesystem makesos.replaceraiseOSError. - Directory durability.
fsyncon the file protects the contents. To also guarantee the rename survives a crash on POSIX, open the directory andfsyncit too. Most scripts skip this step. - Existing links. If the target is a symbolic link,
os.replacereplaces the link itself, not the file it points to. Hard links to the old file keep the old content. - Concurrent writers. The pattern prevents torn reads. It does not merge two writers. The last
os.replacewins, and the other update is lost. - Binary data. For bytes, open with
"wb"and drop the encoding argument.
When to use it
| Situation | Plain `open(..., "w")` | Temporary file + `os.replace` |
|---|---|---|
| Scratch output, logs you can regenerate | Fine | Unnecessary |
| Config or state read by other programs | Risky | Recommended |
| Large file, little free disk space | Works | Needs room for both copies |
| Append-only log | Use `"a"` | Not suitable |
Exercise
Why must the temporary file be created in the same directory as the target, and what happens if it is not?
Show answer
os.replace is atomic only when the source and destination are on the same filesystem. A temporary file in another location, such as /tmp on a different mount, can make os.replace fail with OSError, or force a non-atomic copy, so the guarantee that readers see either the old or the new file is lost. Creating the temporary file with dir=path.parent avoids this.
Exercise
Modify atomicwritetext so that, when the target file already exists, the new file keeps the old file's permissions.
Show answer
Call shutil.copymode(path, tmp_name) before os.replace, guarded by a check such as if path.exists():. Add import shutil at the top. copymode copies the permission bits from the old file onto the temporary file, so after the swap the target keeps its original permissions.