How to Rename Files with Python (os.rename and pathlib)
Updated
Python is a good choice for renaming when the rules get complicated or when the same script has to run on Windows, macOS and Linux. The standard library has everything you need. This guide shows the three rename functions, how they differ between operating systems, and a batch script that previews its changes and never overwrites a file.
Rename a single file
import os
os.rename("report.txt", "report-2026.txt")
from pathlib import Path
Path("notes.md").rename("notes-old.md")Both calls rename the file relative to the current working directory. Path.rename() returns the new path as a Path object (Python 3.8 and later), which is handy when you keep working with the file.
os.rename, os.replace and Path.rename compared
| Function | If the target already exists |
|---|---|
os.rename(src, dst) | Windows: raises FileExistsError. macOS and Linux: silently replaces the target file. |
os.replace(src, dst) | Replaces the target on every system. |
Path.rename(target) | Same behaviour as os.rename. |
Path.replace(target) | Same behaviour as os.replace. |
shutil.move(src, dst) | Also moves between drives or file systems, where os.rename raises OSError. |
Because os.rename behaves differently on Windows and Unix-like systems, a portable script should check for an existing target itself instead of relying on either behaviour.
Useful Path methods for new names
p = Path("photos/IMG_4821.JPG")
p.name # 'IMG_4821.JPG'
p.stem # 'IMG_4821'
p.suffix # '.JPG'
p.with_suffix(".jpg") # photos/IMG_4821.jpg
p.with_stem("lisbon_001") # photos/lisbon_001.JPG (Python 3.9+)
p.with_name("cover.jpg") # photos/cover.jpgBuilding new names with these methods keeps the file in its folder; passing just a bare name to rename() would move the file into the current working directory instead.
A safe batch rename script
The script below numbers all JPG files in a folder in alphabetical order. It starts in dry-run mode and only prints what it would do. Set DRY_RUN = False when the output looks right.
from pathlib import Path
FOLDER = Path("photos")
PREFIX = "lisbon"
DRY_RUN = True
# Collect the list first, so renamed files are not picked up again.
files = sorted(p for p in FOLDER.iterdir() if p.is_file() and p.suffix.lower() == ".jpg")
for i, path in enumerate(files, start=1):
target = path.with_name(f"{PREFIX}_{i:03d}{path.suffix.lower()}")
if target == path:
continue
if target.exists():
print(f"skip {path.name}: {target.name} already exists")
continue
print(f"{path.name} -> {target.name}")
if not DRY_RUN:
path.rename(target)sorted(...)builds the complete list before anything is renamed and fixes the order.p.suffix.lower() == ".jpg"matches.jpgand.JPG;glob("*.jpg")is case-sensitive on Linux but not on Windows.{i:03d}writes the number with three digits: 001, 002, … 999.- The
exists()check prevents overwriting on every operating system.
More rename rules
Replace spaces with underscores
for path in sorted(FOLDER.iterdir()):
if path.is_file() and " " in path.name:
target = path.with_name(path.name.replace(" ", "_"))
if not target.exists():
path.rename(target)Add the modification date as a prefix
import re
from datetime import datetime
for path in sorted(FOLDER.glob("*.pdf")):
if re.match(r"\d{4}-\d{2}-\d{2}_", path.name):
continue # already has a date
date = datetime.fromtimestamp(path.stat().st_mtime).strftime("%Y-%m-%d")
target = path.with_name(f"{date}_{path.name}")
if not target.exists():
path.rename(target)The date is written as 2026-11-23, which sorts chronologically. The re.match line skips files that already start with a date, so running the script twice does not add a second one.
Include subfolders
for path in sorted(FOLDER.rglob("*.jpeg")):
target = path.with_suffix(".jpg")
if not target.exists():
path.rename(target)rglob searches all subfolders; sorted() again collects the full list before the loop starts renaming.
Pitfalls
- Case-only renames on Windows and macOS. Their default file systems ignore case, so
Path("photo.jpg").exists()isTruewhen onlyPhoto.JPGexists. A collision check would then skip a rename fromPhoto.JPGtophoto.jpg, although the rename itself works. Comparetarget.name.lower() == path.name.lower()to detect this case. - Swapping names. Renaming
a.txttob.txtandb.txttoa.txtneeds a temporary third name. - Permissions and open files. On Windows, a file that is open in another program cannot be renamed and raises
PermissionError. CatchOSErrorif the script should continue with the other files. - Invalid characters. Names built from metadata can contain
/,:or?. Replace them before renaming, for example withre.sub(r'[\\/:*?"<>|]', "-", name).
No Python at hand?
For a one-time job, the bulk file renamer on bulkrename.com does numbering and prefixes in the browser without any code. It works on copies and leaves your originals unchanged. Other command-line options are covered in renaming files in Linux and bulk renaming files in Windows.