On this page
os.replace
Prev: os.rename | Up: os | Next: os.rmdir
Rel: os.abort, os.access, os.chdir, os.chmod
Ref: docs.python.org — os.replace
Tags: #public #python3 #stdlib #os
Import
import os
from os import replace
Signature & Overview
os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename a file or directory, overwriting the destination.
Usage
import os
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
tmp_file = Path(tmp) / "data.tmp"
target = Path(tmp) / "data.json"
target.write_text("old", encoding="utf-8")
tmp_file.write_text("new", encoding="utf-8")
os.replace(tmp_file, target)
assert target.read_text(encoding="utf-8") == "new"
Gotchas
- Best primitive for atomic file updates: Overwrites
dstatomically on both POSIX and Windows as long assrcanddstlive on the same filesystem.
REPL Inspect
from os import replace
help(replace)
Linked from
Related notes
- tuts/python3/stdlib_module/os/rename Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/rmdir Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/abort Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/access Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chdir Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chmod Linked here; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/chown shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/close shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/cpu_count shared tags: #os, #stdlib