Use Path("old_name").rename("new_name") from Python’s built-in pathlib module (or os.rename("old_name", "new_name"))—preferring Path.replace("new_name") (or os.replace()) when you need cross-platform atomic overwriting if "new_name" already exists, and falling back to shutil.move("old_name", "new_name") when moving/renaming across different disk drives or filesystems.
Basic Example
from pathlib import Path
# 1. Recommended: Rename a file or folder in the same directory using `pathlib.Path.rename()`
src_file = Path("draft_report.txt")
dst_file = src_file.rename("final_report.txt") # Returns the new Path("final_report.txt")
print(dst_file)
# Output: final_report.txt
# 2. Rename a directory (works identically for folders and files):
Path("old_folder").rename("new_folder")
# 3. Rename only the filename while keeping the parent directory intact (`with_name` / `with_stem`):
nested = Path("data/2026/sales_raw.csv")
renamed_nested = nested.rename(nested.with_stem("sales_clean")) # -> Path("data/2026/sales_clean.csv")
Key Details & Edge Cases
Path.rename()vs.Path.replace()when the destination already exists (Windows vs. POSIX):- On Windows,
Path("a.txt").rename("b.txt")raisesFileExistsError:if"b.txt"already exists, whereas on Linux/macOS it silently overwrites an existing file. UsePath("a.txt").replace("b.txt")whenever you want consistent, atomic cross-platform overwrite semantics, or checkif not dst.exists():before.rename()when overwriting must be prevented.
- On Windows,
- Cross-drive or cross-filesystem renames (
OSError: [Errno 18] Invalid cross-device link):- Both
Path.rename()andos.rename()perform an instant metadata-only directory entry update on the same filesystem. Moving fromC:\toD:\on Windows or/tmpto/mnt/storageon Linux raisesOSError: [Errno 18] Invalid cross-device link—useshutil.move("src", "dst")whenever the source and destination may reside on different drives or mount points.
- Both
- Missing parent directories (
FileNotFoundError):- Renaming into a subfolder that does not exist yet (e.g.,
Path("a.txt").rename("archive/2026/a.txt")) raisesFileNotFoundError. Create parent folders first viadst.parent.mkdir(parents=True, exist_ok=True).
- Renaming into a subfolder that does not exist yet (e.g.,
- Windows file-in-use locks (
PermissionError:):- On Windows, renaming a file or folder that is currently open in Python, an editor, or a terminal working directory raises
PermissionError. Ensure allwith open(...)blocks are closed and no shell/process has its current working directory inside the folder before renaming.
- On Windows, renaming a file or folder that is currently open in Python, an editor, or a terminal working directory raises
- Case-only renames on case-insensitive filesystems (Windows NTFS / macOS APFS):
- Renaming
readme.md$\rightarrow$README.mdwithPath("readme.md").rename("README.md")works directly in Python on Windows/macOS, though Git may still track the old casing unless updated viagit mv.
- Renaming
- Avoiding
os.renames()unintended cleanup:os.renames(old, new)creates missing destination parent directories automatically, but also recursively deletes empty source parent directories afterward—stick todst.parent.mkdir(parents=True, exist_ok=True)+src.rename(dst)unless you explicitly want empty source folders pruned.
Comparison of File & Folder Renaming Methods in Python
| Method | Overwrites Existing File Cross-Platform? | Works Across Different Drives / Mounts? | Return Value | Best Used When |
|---|---|---|---|---|
Path(src).rename(dst) (Recommended) |
No (raises FileExistsError on Windows; overwrites on POSIX) |
No (raises OSError cross-device) |
New Path object |
Standard same-directory or same-drive file/folder renames in modern Python. |
Path(src).replace(dst) (Recommended for atomic overwrite) |
Yes (atomic replace on Windows, Linux, and macOS) | No (raises OSError cross-device) |
New Path object |
Atomic file updates (writing to a .tmp file and replacing the live target safely). |
shutil.move(src, dst) |
Overwrites if dst is a file path; moves inside if dst is an existing dir |
Yes (copies then deletes across drives) | Destination path string | Moving/renaming files or directories across arbitrary disks, USB drives, or mount points. |
os.rename(src, dst) / os.replace(src, dst) |
os.replace: Yes; os.rename: OS-dependent |
No | None |
Low-level scripts operating purely on string paths without importing pathlib. |
You must log in or register to comment.
