Python Glossary Русский

Python 3.3+osfunction

os.replace()

os — renaming/moving

Renames a file, overwriting an existing target the same way on every OS. Within one file system the replacement is atomic.

Syntax

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

The key difference from os.rename: if the target exists, rename fails with FileExistsError on Windows and silently replaces it on Linux, whereas replace overwrites everywhere. Atomicity gives safe saving: write to a temporary file next to the target and replace — a reader sees either the old version or the new one, never half. 'Next to' matters: across file systems (another drive, /tmp) you get OSError with EXDEV and need shutil.move. A directory cannot be replaced by a file — IsADirectoryError or PermissionError.

Examples

import os
with open('config.json', 'w', encoding='utf-8') as f:
    f.write('{"v": 1}')
with open('config.json.tmp', 'w', encoding='utf-8') as f:
    f.write('{"v": 2}')
os.replace('config.json.tmp', 'config.json')
with open('config.json', encoding='utf-8') as f:
    print(f.read())  # → {"v": 2}
print(os.path.exists('config.json.tmp'))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy