Skip to main content

How to Replace a File Safely in Python with a Temporary File and Path.replace

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

If a program stops while it's writing a file, because of an error, a full disk or a power cut, the file is left half-written. The safe way to update a file is to write the new version to a temporary file next to it and then swap it in with Path.replace(): the old file stays whole until the new one is complete. This guide does it on Python 3.15.2.

Syntax​

Syntax
temporary = <target>.with_name(<target>.name + ".tmp")
temporary.write_text(<new content>, encoding="utf-8")
temporary.replace(<target>)
PartWhat it means
<target>A pathlib.Path to the file you're updating
<target>.with_name(<target>.name + ".tmp")A path to a temporary file in the same folder, such as settings.txt.tmp
write_text(<new content>, ...)Writes the whole new version to the temporary file
temporary.replace(<target>)Renames the temporary file to the target's name, replacing the old file

The pathlib documentation says replace() will "Rename this file or directory to the given target", and "If target points to an existing file or empty directory, it will be unconditionally replaced." It's built on os.replace(), whose documentation adds: "If successful, the renaming will be an atomic operation (this is a POSIX requirement)." Atomic means other programs see either the old file or the new one, never a mix.

The Example​

The script creates settings.txt with the line theme=light, writes theme=dark to settings.txt.tmp, swaps it in with replace(), and prints the file and whether the temporary file is still there.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

replace_settings.py
from pathlib import Path

settings = Path("settings.txt")
settings.write_text("theme=light\n", encoding="utf-8")

temporary = settings.with_name(settings.name + ".tmp")
temporary.write_text("theme=dark\n", encoding="utf-8")
temporary.replace(settings)

print(settings.read_text(encoding="utf-8"), end="")
print("Temporary file still there:", temporary.exists())

The replace_settings.py script in a macOS-style code window: it writes theme=light to settings.txt, writes theme=dark to settings.txt.tmp, calls temporary.replace(settings), and prints the file and whether the temporary file exists.

  • The first write_text() only sets up the example: it gives settings.txt its old content.
  • settings.with_name(settings.name + ".tmp") builds the path settings.txt.tmp in the same folder. Keeping it in the same folder matters, as the Common Mistakes table shows.
  • temporary.replace(settings) swaps the new file in, in one step.

Step 2: Run It​

Terminal
uv run python replace_settings.py
Output
theme=dark
Temporary file still there: False

The terminal after uv run python replace_settings.py: theme=dark, then Temporary file still there: False.

settings.txt now holds the new line, and the temporary file is gone, because replace() renamed it rather than copying it. Until that last step, settings.txt still held its complete old content. The command works unchanged in PowerShell.

Why Not Write the File Directly?​

Here's what happens when an error stops a program halfway through writing the real file. This script opens half.txt, which holds theme=light, for writing, writes part of the new line, and then raises an error:

half_written.py
from pathlib import Path

settings = Path("half.txt")
settings.write_text("theme=light\n", encoding="utf-8")

try:
with settings.open("w", encoding="utf-8") as file:
file.write("theme=")
raise RuntimeError("Something went wrong halfway")
except RuntimeError as error:
print("Error:", error)

print(repr(settings.read_text(encoding="utf-8")))
Terminal
uv run python half_written.py
Output
Error: Something went wrong halfway
'theme='

The old content was gone the moment the file was opened with "w", and the new content never finished. With a temporary file, the same error would only have left a broken .tmp file behind, and settings.txt would still be whole.

Common Mistakes​

MistakeWhat happensDo this instead
Writing the real file directlyAn error halfway leaves it half-written, as aboveWrite a temporary file, then replace()
Putting the temporary file in another folder, such as the system's temp folderThe os.replace() docs warn: "The operation may fail if src and dst are on different filesystems"Keep it next to the target with with_name()
Using rename() insteadWorks on macOS and Linux, but the docs say "On Windows, if target exists, FileExistsError will be raised"Use replace(), which replaces the target everywhere
Replacing onto a folder that has files in itIsADirectoryError: [Errno 21] Is a directory: 'settings.txt.tmp' -> 'settings_folder'Point it at the file's own path

Troubleshooting​

SymptomLikely causeFix
FileExistsError on Windowsrename() was used and the target existsSwitch to replace()
A .tmp file is left behindThe program stopped before replace()Delete it; the target still holds its old, complete content

FAQ​

Is replace() a copy?​

No, it's a rename. The temporary file stops existing and its content becomes the target, which is why the example printed Temporary file still there: False.

Does rename() replace an existing file?​

On macOS and Linux, yes: a rename() onto an existing rename_target.txt gave it the new content. On Windows it raises FileExistsError, so replace() is the one to use when the code has to run everywhere.

Conclusion​

The script wrote the new version to settings.txt.tmp and swapped it in with replace(), so settings.txt went straight from theme=light to theme=dark. Written directly, the same file was left as 'theme=' after an error. Keep the temporary file in the same folder, and use replace(), not rename().

Additional Resources​