Path.rename
Both call the OS rename. The difference is an existing target: replace() always overwrites it (os.replace); rename() raises FileExistsError on Windows but silently overwrites on Linux and macOS (os.rename). A relative target is relative to the current directory, not to the file.
Demo
from pathlib import Path Path('draft.txt').write_text('v1', encoding='utf-8') new = Path('draft.txt').rename('final.txt') (new.as_posix(), Path('draft.txt').exists(), new.read_text(encoding='utf-8'))
rename() returns a Path for the target; the old name no longer exists. Renaming a file to its own name is allowed and changes nothing. Moving into a folder that does not exist raises FileNotFoundError (its message is OS-specific, so it is not shown here).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| target | str | os.PathLike | yes | New location. Relative targets are resolved against the current working directory. |
Return value
Path — A new Path for target (3.8+). The original Path object still names the old location.
Common patterns
from pathlib import Path p = Path('photos/IMG_0042.jpg') p.rename(p.with_name('cat.jpg'))
from pathlib import Path target = Path('state.json') tmp = target.with_name(target.name + '.tmp') tmp.write_text(data, encoding='utf-8') tmp.replace(target)
from pathlib import Path src = Path('inbox/invoice.pdf') src.replace(Path('archive') / src.name)
Examples
Pitfalls
from pathlib import Path Path('docs').mkdir() Path('docs/a.txt').touch() Path('docs/a.txt').rename('b.txt').as_posix()
from pathlib import Path Path('docs').mkdir() Path('docs/a.txt').touch() p = Path('docs/a.txt') p.rename(p.with_name('b.txt')).as_posix()
import os from pathlib import Path Path('a').touch() Path('b').touch() try: Path('a').rename('b') result = 'overwritten' except FileExistsError: result = 'FileExistsError' result == ('FileExistsError' if os.name == 'nt' else 'overwritten')
from pathlib import Path Path('a').write_text('new', encoding='utf-8') Path('b').write_text('old', encoding='utf-8') Path('a').replace('b') Path('b').read_text(encoding='utf-8')
from pathlib import Path p = Path('v1.txt') p.touch() p.rename('v2.txt') p.exists()
from pathlib import Path p = Path('v1.txt') p.touch() p = p.rename('v2.txt') p.exists()
When to use
- Renaming or moving within one file system
- Atomic updates: write a temp file, then replace()
- Moving across drives / file systems → shutil.move (rename fails with OSError there)
- Copying → shutil.copy2 (Path.copy arrives in 3.14)
Notes
FAQ
p.rename(p.with_name('new-name.txt')) — building the target from p keeps the file in the same folder. The method returns the new Path.