Sub topic 13
Writing files safely with a temporary file
This chapter assumes you can use open() and with, write text with an explicit encoding, build paths with pathlib, and catch exceptions with try/except. It builds on the earlier chapters about write modes and error handling.
The problem with writing in place
Opening a file with mode "w" truncates it immediately. The old content is gone before your program writes the first new byte. If anything fails between open() and the last write(), the file is left empty or partly written.
from pathlib import Path
target = Path("settings.json")
target.write_text('{"version": 1}\n', encoding="utf-8")
try:
with open(target, "w", encoding="utf-8") as f:
f.write('{"version": ')
raise RuntimeError("crash while writing")
except RuntimeError:
pass
print(repr(target.read_text(encoding="utf-8")))The output is '{"version": '. The valid version 1 file has been replaced by broken JSON. A real crash, a power loss, or a full disk produces the same result. A reader that opens the file during the write sees the same partial content.
The fix is to never modify the real file until a complete replacement exists. You write the new content to a temporary file, then swap it into place in a single step.
The pattern
- Create a temporary file in the same directory as the target.
- Write the full new content to it.
- Flush Python's buffer and ask the operating system to push the data to disk.
- Replace the target with the temporary file using
os.replace. - If anything fails, delete the temporary file and re-raise the error.
The implementation
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)
raiseEach part has a job.
tempfile.mkstemp(dir=path.parent, suffix=".tmp")creates a new, uniquely named file and returns an open low-level file descriptorfdand its name. The name is unpredictable, so two processes writing the same target do not collide on the temporary file. On POSIX systems the file is created with mode0o600, readable only by its owner.os.fdopen(fd, "w", encoding=encoding)wraps the descriptor in a normal text file object. Thewithblock closes it, which also closesfd. You do not callos.close(fd)yourself.tmp.flush()moves data from Python's buffer to the operating system.os.fsync(tmp.fileno())asks the operating system to write its cache to the storage device.os.replace(tmp_name, path)renames the temporary file over the target.except BaseExceptionalso catchesKeyboardInterrupt, so Ctrl+C does not leave stray.tmpfiles. Theraiseat the end passes the original error on, so the caller still sees it.unlink(missing_ok=True)does not fail if the temporary file is already gone.
Now repeat the earlier failure test with this function. Passing None as the text makes tmp.write raise a TypeError partway through.
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
target = Path("settings.json")
atomic_write_text(target, '{"version": 1}\n')
try:
atomic_write_text(target, None)
except TypeError as exc:
print("write failed:", exc)
print(repr(target.read_text(encoding="utf-8")))
print(sorted(p.name for p in Path(".").glob("*.tmp")))The target still contains '{"version": 1}\n', and the list of leftover .tmp files is empty.
Why the temporary file must be in the same directory
os.replace is only atomic when the source and destination are on the same filesystem. The default location of tempfile.NamedTemporaryFile() and mkstemp() is the system temp directory, such as /tmp. That is often a different filesystem from your data. Renaming across filesystems fails with OSError (EXDEV, "Invalid cross-device link"). Python does not fall back to copying for os.replace. shutil.move does fall back to copy-then-delete, but that copy is not atomic, so it defeats the purpose.
Passing dir=path.parent puts the temporary file next to the target, so both are on the same filesystem.
What "atomic" guarantees
On POSIX systems, os.replace maps to rename(2). Another process that opens the target sees either the old file or the new one, never a mix. A reader that already has the old file open keeps reading the old content, because it holds the old file, not the name.
On Windows, os.replace also overwrites an existing destination, unlike os.rename. It raises PermissionError if another process has the target open without sharing rights. Be ready to catch that error or retry.
The guarantee covers the swap. It does not cover everything around it:
- Concurrent writers. Two processes can each write a complete temporary file and replace in turn. Neither file is corrupted, but the later one wins and the earlier update is lost. Atomic replace is not a lock. If you need a read-modify-write cycle, use a lock file or a database.
- Symlinks. If
pathis a symlink,os.replacereplaces the link itself, not the file it points to. CallPath(path).resolve()first if you want to update the target of the link. - Hard links. Other names that pointed to the old file keep pointing to the old content.
Durability: fsync and the directory
flush() and fsync() do different things. flush() empties Python's own buffer into the operating system. fsync() makes the operating system write its cached data to the device. Without fsync, a power loss shortly after os.replace can leave a correctly named file with empty or partial content on some filesystems, because the rename can reach disk before the data does.
There is one more gap. The rename is a change to the directory, and that change also sits in a cache. On POSIX systems you can sync the directory itself. Windows does not allow opening a directory this way, so the helper below skips it there.
import os
import shutil
import tempfile
from pathlib import Path
def _fsync_directory(directory):
if os.name != "posix":
return
fd = os.open(directory, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_write_bytes(path, data):
path = Path(path)
fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "wb") as tmp:
tmp.write(data)
tmp.flush()
os.fsync(tmp.fileno())
if path.exists():
shutil.copymode(path, tmp_name)
os.replace(tmp_name, path)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raise
_fsync_directory(path.parent)
atomic_write_bytes("blob.bin", b"\x00\x01\x02")
print(Path("blob.bin").read_bytes())This version differs from the first in three ways.
- It writes bytes, so there is no encoding or newline translation. Binary mode
"wb"takes noencodingargument. - It copies the permission bits of the existing file onto the temporary file with
shutil.copymode. Without this, a file that was0o644becomes0o600after the first safe write, becausemkstempcreates private files. If the target does not exist yet, you may want to set the mode you actually intend withos.chmod. - It syncs the directory after the replace. This sits outside the
tryblock, because after a successful replace there is no temporary file to clean up.
Each fsync is slow, often milliseconds on a hard disk. Skip it for caches and files you can regenerate. Keep it for data you cannot recreate.
Failure modes to expect
| Situation | Result | What to do |
|---|---|---|
| Exception while writing | Old target intact, temp file deleted | Handle or log the error |
| Process killed (`SIGKILL`) or power loss before replace | Old target intact, `.tmp` file left behind | Clean up stale `*.tmp` files at startup |
| Power loss after replace, without `fsync` | Target may be empty or partial on some filesystems | Keep the `fsync` calls |
| Target directory missing | `mkstemp` raises `FileNotFoundError` | Call `path.parent.mkdir(parents=True, exist_ok=True)` first |
| Directory not writable | `mkstemp` raises `PermissionError` | You need write access to the directory, not only to the file |
| Disk full | `write` or `fsync` raises `OSError` | The old file survives, because the failure happens before the replace |
| Temp and target on different filesystems | `os.replace` raises `OSError` | Keep `dir=path.parent` |
The except block cannot run when the process is killed outright, so stale temporary files are possible. Using a recognizable suffix such as .tmp makes them easy to find and delete.
The directory-permission row matters. Normal in-place writing needs permission on the file only. The temporary-file approach needs permission to create and rename entries in the directory. A file you may edit in a directory you may not write to cannot be updated this way.
When to use it
Use the pattern for files that other code reads and that must always be valid: configuration, JSON state, indexes, and generated output that tools consume. It is a poor fit for append-only logs, where you want "a" mode, and for very large files, where writing a full second copy costs disk space and time. When you need many concurrent updates, a database such as SQLite handles transactions for you.
Exercise
Your function calls tempfile.mkstemp() with no arguments, then os.replace(tmp_name, "/data/report.csv"). It works on your laptop but raises OSError: Invalid cross-device link on the server. What is the cause, and what is the fix?
Show answer
By default, mkstemp creates the file in the system temp directory, such as /tmp. On the server that directory is on a different filesystem from /data, and os.replace cannot rename across filesystems. Pass dir= with the target's parent directory, for example tempfile.mkstemp(dir=Path("/data/report.csv").parent), so both files are on the same filesystem.
Exercise
After switching to atomic_write_text, a deployment script notices that config.ini changed from mode 0o644 to 0o600, and other users can no longer read it. Why did this happen, and how do you preserve the original permissions?
Show answer
mkstemp creates the temporary file with mode 0o600, and os.replace moves that file, with its permissions, over the target. Before the replace, copy the mode from the old file when it exists, for example shutil.copymode(path, tmp_name) inside if path.exists():. For a new file, set the intended mode with os.chmod(tmp_name, 0o644).
Exercise
You remove tmp.flush() and os.fsync(tmp.fileno()) from atomic_write_text because the code seems to work. Name one failure this reintroduces, and say whether a normal Python exception can trigger it.
Show answer
After a power loss or system crash, the renamed file can exist with empty or partial content. The operating system may have recorded the rename before it wrote the file data to disk. A normal Python exception cannot trigger this, because the exception handler deletes the temporary file before the replace. The risk comes from a crash of the machine or operating system after the replace.