On this page
os.rename
Prev: os.removedirs | Up: os | Next: os.replace
Rel: os.abort, os.access, os.chdir, os.chmod
Ref: docs.python.org — os.rename
Tags: #public #python3 #stdlib #os
Import
import os
from os import rename
Signature & Overview
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename a file or directory.
Usage
import os
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
a, b = Path(tmp) / "a.txt", Path(tmp) / "b.txt"
a.write_text("v1", encoding="utf-8")
os.rename(a, b)
assert not a.exists() and b.read_text(encoding="utf-8") == "v1"
Gotchas
- Fails on Windows if
dstalready exists: Useos.replace()for atomic cross-platform overwrite, orshutil.move()across filesystems.
REPL Inspect
from os import rename
help(rename)
Linked from
Related notes
- tuts/python3/stdlib_module/os/removedirs Linked here; links to this page; shared tags: #os, #stdlib
- tuts/python3/stdlib_module/os/replace 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