Python 3.4+pathlibfunction
.rename()
operations
Rename (move) the path and return the new Path; behaviour when the target exists is platform-dependent and raises on Windows.
Syntax
p.rename(target)
A relative target is resolved against the current working directory, not against p's own directory, so p.rename('backup.txt') lands the file wherever the script was launched from. Overwriting an existing target is platform-dependent — silent on POSIX, FileExistsError on Windows — so use replace() when you want one behaviour everywhere, and shutil.move() across filesystem boundaries, where rename() fails with OSError. p itself is unchanged; keep working with the returned Path.
Examples
from pathlib import Path
f = Path('old_path.txt')
f.write_text('data')
new = f.rename('new_path.txt')
new.name # → 'new_path.txt'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy