How to Rename Files with Python: os.rename, pathlib and Bulk Scripts
To change a file name in Python, call os.rename("old.txt", "new.txt"), or with pathlib, Path("old.txt").rename("new.txt"). Both rename the file in place. If a file with the new name might already exist and you want it replaced on every operating system, use os.replace() instead; and to move a file to a different drive, use shutil.move().
The rest of this guide shows the differences between those functions, then builds up to safe bulk renaming: looping over a folder with pathlib, regular expressions, sequential numbers, a dry-run switch, collision checks and an undo log. Every snippet was run with Python 3.12 on Linux; the pathlib snippets need Python 3.9 or later.
Rename a single file
os.rename
import os
os.rename("old.txt", "new.txt")Paths are relative to the current working directory (where you ran the script from, not where the script lives). Use full paths to be explicit:
os.rename("/home/sam/Downloads/scan.pdf", "/home/sam/Downloads/lease-2026.pdf")os.rename returns nothing. If the source doesn't exist, it raises FileNotFoundError:
FileNotFoundError: [Errno 2] No such file or directory: 'nope.txt' -> 'x.txt'pathlib.Path.rename
pathlib is the modern, object-oriented way to work with paths, and it makes bulk renames much easier to write:
from pathlib import Path
new_path = Path("old.txt").rename("new.txt")
print(new_path) # new.txtSince Python 3.8, Path.rename() returns the new Path, which is handy for chaining. The real power is in the helpers that build the new name for you:
p = Path("photos/IMG_0001.jpg")
p.with_name("beach.jpg") # photos/beach.jpg
p.with_stem("beach") # photos/beach.jpg (Python 3.9+)
p.with_suffix(".png") # photos/IMG_0001.png
p.stem, p.suffix, p.name # ('IMG_0001', '.jpg', 'IMG_0001.jpg')These only create new path objects; nothing on disk changes until you call rename().
os.rename vs os.replace vs Path.rename vs shutil.move
| Function | If the new name already exists | Across drives or filesystems |
|---|---|---|
os.rename(src, dst) | Replaced silently on Linux and macOS; FileExistsError on Windows | Fails with OSError |
os.replace(src, dst) | Replaced silently on all systems | Fails with OSError |
Path.rename(target) | Same as os.rename | Fails with OSError |
Path.replace(target) | Same as os.replace | Fails with OSError |
shutil.move(src, dst) | Replaced if dst is an existing file | Works: copies, then deletes the original |
The first row is the most important one. On Linux and macOS, os.rename overwrites an existing file without warning, so the same script that raises an error on Windows quietly destroys data on a Mac. Don't rely on either behaviour: check for the target yourself (shown below) and use os.replace only when overwriting is what you want.
Moving to another drive: shutil.move
A rename only changes a directory entry, so it can't cross filesystems. Renaming from your home directory to a USB drive fails:
OSError: [Errno 18] Invalid cross-device link: '/root/report.pdf' -> '/mnt/usb/report.pdf'shutil.move handles that case by copying the file and deleting the original, and falls back to a plain rename when it can:
import shutil
shutil.move("/home/sam/report.pdf", "/mnt/usb/report.pdf")Bulk rename files with pathlib
Change every extension in a folder
from pathlib import Path
folder = Path("photos")
for path in folder.glob("*.jpeg"):
path.rename(path.with_suffix(".jpg"))Watch out: glob() is case-sensitive on Linux, so "*.jpeg" won't match IMG_01.JPEG there (it will on Windows and on a default Mac drive). To catch every case, loop over all files and compare path.suffix.lower(), as the next examples do.
Include subfolders with rglob
rglob() searches recursively:
from pathlib import Path
for path in Path("projects").rglob("*.txt"):
path.rename(path.with_suffix(".md"))Clean up names: lowercase, hyphens, no special characters, with a dry run
This is the pattern to copy for real work. It builds each new name, prints what it would do, skips anything that would overwrite another file, and only renames when you switch DRY_RUN off:
import re
from pathlib import Path
DRY_RUN = True # set to False to actually rename
folder = Path("downloads")
for path in sorted(folder.iterdir()):
if not path.is_file():
continue
stem = path.stem.lower()
stem = re.sub(r"[^a-z0-9]+", "-", stem).strip("-")
new_path = path.with_name(stem + path.suffix.lower())
if new_path == path:
continue
if new_path.exists() and not new_path.samefile(path):
print(f"SKIP {path.name}: {new_path.name} already exists")
continue
print(f"{path.name} -> {new_path.name}")
if not DRY_RUN:
path.rename(new_path)Output on a test folder:
SKIP Already Fine.txt: already-fine.txt already exists
My Holiday Photo.JPG -> my-holiday-photo.jpg
Report Final (v2).PDF -> report-final-v2.pdfThree details make this safe:
- `sorted()` makes the order predictable, so the dry run and the real run do the same thing.
- `new_path.exists()` prevents one file from overwriting another when two names clean up to the same result.
- `not new_path.samefile(path)` handles case-only renames on Windows and macOS. Those filesystems are case-insensitive, so
notes.txt"exists" when you're renamingNotes.TXT;samefilerecognises that it's the same file and lets the rename go ahead.
The regular expression [^a-z0-9]+ replaces every run of characters that isn't a lowercase letter or digit with a single hyphen, which also removes the spaces that cause trouble in URLs and scripts (see spaces in file names).
Rename with regular expressions
Regex is the right tool when names follow a pattern you want to rearrange. This turns phone-camera names like IMG_20260704_183015.JPG into 2026-07-04_183015.jpg and ignores everything else:
import re
from pathlib import Path
pattern = re.compile(r"^IMG_(\d{8})_(\d{6})(\.\w+)$")
for path in Path("camera").iterdir():
match = pattern.match(path.name)
if not match:
continue
date, time, ext = match.groups()
new_name = f"{date[:4]}-{date[4:6]}-{date[6:]}_{time}{ext.lower()}"
print(f"{path.name} -> {new_name}")
path.rename(path.with_name(new_name))Use raw strings (r"...") for patterns so backslashes reach the regex engine untouched. For more pattern recipes, see rename files with regex.
Number files in sequence
enumerate plus an f-string with zero padding gives names that sort correctly:
from pathlib import Path
folder = Path("trip")
files = sorted(p for p in folder.iterdir() if p.suffix.lower() == ".jpg")
for i, path in enumerate(files, start=1):
new_path = path.with_name(f"lisbon-2026-{i:03d}{path.suffix.lower()}")
if new_path.exists():
raise SystemExit(f"Stopping: {new_path.name} already exists")
path.rename(new_path)
print(f"{path.name} -> {new_path.name}"){i:03d} produces 001, 002 and so on. Note that sorted() sorts alphabetically, so DSC0010 comes after DSC0002 only because the camera zero-padded its numbers; for unpadded names, sort by modification time with key=lambda p: p.stat().st_mtime. The sequential renaming guide covers ordering choices.
Rename files from a CSV mapping
When someone hands you a spreadsheet of old and new names, save it as a two-column CSV without a header and let Python apply it:
import csv
from pathlib import Path
folder = Path("contracts")
with open("names.csv", newline="") as f:
for old, new in csv.reader(f):
src = folder / old
dst = folder / new
if not src.exists():
print(f"missing: {old}")
elif dst.exists():
print(f"exists, skipped: {new}")
else:
src.rename(dst)The same approach in other tools is covered in bulk rename files from a list.
Keep an undo log
Renames can't be undone with Ctrl+Z. Writing every change to a CSV gives you a way back:
import csv
from pathlib import Path
folder = Path("scans")
with open("rename-log.csv", "w", newline="") as log:
writer = csv.writer(log)
writer.writerow(["old", "new"])
for path in sorted(folder.iterdir()):
if path.suffix.lower() != ".pdf":
continue
new_path = path.with_name("invoice-" + path.name.lower())
path.rename(new_path)
writer.writerow([str(path), str(new_path)])And to reverse it:
import csv
from pathlib import Path
with open("rename-log.csv", newline="") as log:
for row in csv.DictReader(log):
Path(row["new"]).rename(row["old"])Windows quirks
- Overwriting:
os.renameandPath.renameraiseFileExistsErrorif the target exists. Useos.replaceif you really mean to overwrite. - Files in use: if another program has the file open, Windows refuses the rename with
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process. Close the file (often Excel, Word or a PDF viewer) and retry. - Backslashes in paths: write
r"C:\Users\sam\Documents\report.pdf"as a raw string, or use forward slashes, which Python accepts on Windows. In a normal string,"\t"would become a tab. - Forbidden characters: Windows names can't contain
\ / : * ? " < > |or end with a space or period, and names such asCON,PRN,AUX,NUL,COM1andLPT1are reserved. A clean-up function like the one above that keeps only letters, digits and hyphens avoids all of these. - Long paths: paths over 260 characters can fail unless long path support is enabled in Windows and Python.
When the name has to come from the content
Python is excellent when the new name can be computed from the old one, a date, a counter or a spreadsheet. It's much harder when the name should describe what's in the file: a scanned receipt, a photo, a contract. That needs OCR or an image model in your script. File Renamer AI does that part in the browser: upload up to 100 photos, PDFs or documents per batch, review the names the AI suggests, and download the renamed files. For simple rule-based jobs without code, the free online bulk renamer runs entirely in your browser.
Frequently Asked Questions
How do I rename a file in Python?
Use os.rename("old.txt", "new.txt") or, with pathlib, Path("old.txt").rename("new.txt"). Paths are relative to the current working directory unless you pass full paths. Use os.replace if you want an existing file with the new name to be overwritten on every operating system.
What is the difference between os.rename and os.replace?
If the destination already exists, os.replace always overwrites it, while os.rename overwrites it on Linux and macOS but raises FileExistsError on Windows. Neither can move a file to a different drive or filesystem; use shutil.move for that.
How do I rename multiple files in Python?
Loop over the folder with pathlib, for example for path in Path("photos").glob("*.jpeg"): path.rename(path.with_suffix(".jpg")). For real work, print each planned rename first, check that the target name does not already exist, and keep a log of old and new names.
How do I rename a file without overwriting an existing one?
Check before renaming: if not new_path.exists(): path.rename(new_path). On case-insensitive systems like Windows and macOS, also allow case-only renames by checking new_path.samefile(path). Avoid os.replace when you do not want to overwrite anything.
Why does os.rename fail with Invalid cross-device link?
A rename can only change a name within one filesystem. Moving a file to another drive, partition or mounted volume needs a copy and delete, which shutil.move does for you. Replace os.rename with shutil.move for those cases.
How do I change only the file extension in Python?
Use pathlib's with_suffix: path.rename(path.with_suffix(".jpg")). It replaces the last suffix and keeps the rest of the name. Changing the extension does not convert the file format; it only changes the name.
Free tools
Related Posts
How to Rename Files in Linux: mv, rename, Bash Loops and GUI Tools
How to rename a file in Linux with mv, rename directories, use both rename commands safely, and bulk rename files with bash loops, find and GUI file renamers.
MacHow to Rename Files in Mac Terminal: mv, zsh Loops and zmv
Rename files from the Mac Terminal with mv, handle spaces and case-only changes, and bulk rename safely with zsh loops and zmv, with dry runs that preview first.
AdvancedHow to Rename Columns in R (dplyr, Base R and data.table)
Rename columns in R with dplyr::rename(new = old), rename_with for patterns, base R names() and colnames(), or data.table setnames. Examples for every case.
Ready to organize your files?
Try AI renaming right away. No sign-up needed until you download.
Try It Free