Python Glossary Русский

Python 3.4+pathlibfunction

.replace()

operations

Rename the path, unconditionally replacing the target if it exists — unlike `.rename()`, behaves the same on every platform.

Syntax

p.replace(target)

The overwrite is unconditional: whatever sat at the target path is gone silently, no prompt and no recycle bin. Across filesystem boundaries (a different drive or mount point) the call raises OSError — use shutil.move() for that. Within one filesystem the swap happens in a single step, which is why "write a temp file next to it, then replace the real one" is the standard way to avoid leaving a half-written file behind after a crash.

Examples

from pathlib import Path
src = Path('src.txt'); src.write_text('new')
dst = Path('dst.txt'); dst.write_text('old')
src.replace(dst) # → dst перезаписан
dst.read_text() # → 'new'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy