Python Scripting

Automating File Renaming With Python

By ScriptChest Editorial Team · · 3 min read

Renaming files by hand is dull work, and it gets worse as the count grows. Photos from a camera, exported reports, downloaded documents: they tend to arrive with names that make sorting and searching harder than it should be. Python can fix a whole folder in seconds, and the standard library already has what you need.

This guide builds up from a tiny rename to a reusable script with a safety net. Everything uses the pathlib module, which ships with Python, so there is nothing to install.

Start by listing what you have

Before changing anything, look at the files. The Path class makes this easy.

from pathlib import Path

folder = Path("photos")
for item in sorted(folder.iterdir()):
    if item.is_file():
        print(item.name)

Each item is a Path object with useful parts: item.name is the full file name, item.stem is the name without the extension, and item.suffix is the extension including the dot. Knowing these three pieces covers most renaming tasks.

Rename a single file

The rename method moves a file to a new path in the same filesystem.

old = Path("photos/IMG_0042.jpg")
new = old.with_name("holiday_042.jpg")
old.rename(new)

The with_name method builds a new path by swapping only the file name. There is also with_stem (Python 3.9 and later) and with_suffix, which change just one part. For example, old.with_suffix(".png") changes the extension without touching the name.

Add a prefix and number files in order

A common job is to give files a consistent, sorted numbering.

from pathlib import Path

folder = Path("scans")
files = sorted(p for p in folder.iterdir() if p.is_file())

for number, path in enumerate(files, start=1):
    new_name = f"scan_{number:03d}{path.suffix.lower()}"
    path.rename(path.with_name(new_name))

The format code :03d pads the number with zeros, so you get scan_001, scan_002 and so on. Padding matters because plain text sorting puts scan_10 before scan_2. Lowercasing the suffix also tidies up files that mix .JPG and .jpg.

Clean up names with regular expressions

When names contain spaces, brackets or repeated characters, the re module helps.

import re

def clean(name: str) -> str:
    name = name.lower()
    name = re.sub(r"[^a-z0-9._-]+", "_", name)
    name = re.sub(r"_+", "_", name)
    return name.strip("_")

The first substitution replaces any run of unusual characters with an underscore. The second collapses repeated underscores. The function returns a name that is safe on nearly every operating system and friendly to command line tools.

Always do a dry run first

Renames are easy to get wrong and awkward to undo. A dry run prints what would happen without touching anything. Make it the default behaviour.

import sys
from pathlib import Path

def plan(folder: Path):
    for path in sorted(folder.iterdir()):
        if path.is_file():
            new_name = clean(path.stem) + path.suffix.lower()
            if new_name != path.name:
                yield path, path.with_name(new_name)

def main():
    folder = Path(sys.argv[1])
    apply = "--apply" in sys.argv
    for old, new in plan(folder):
        if new.exists():
            print(f"SKIP (exists): {new.name}")
            continue
        print(f"{old.name} -> {new.name}")
        if apply:
            old.rename(new)

if __name__ == "__main__":
    main()

Run it as python rename.py photos to preview, then python rename.py photos --apply to commit the changes. The exists check is important. Without it, renaming onto an existing file can overwrite it on some systems, and you would lose data.

Handle collisions and special cases

Real folders are messy, so plan for these situations:

  • Two files that clean up to the same name. Add a counter, such as _2, until the name is free.
  • Hidden files, such as those that start with a dot. Skip them unless you mean to rename them.
  • Subfolders. Use folder.rglob("*") to walk them, but be sure that is what you want.
  • Case only changes on case-insensitive filesystems. Renaming Photo.jpg to photo.jpg may need a temporary name in between.
  • Dates. If you want to name files by modification time, read it with path.stat().st_mtime and format it with datetime.

Keep a record of what changed

For larger jobs, write each old and new name to a text file as you go. A simple log lets you reverse the operation later if you notice a mistake. Even a plain list of old -> new lines is enough to rebuild the original names with a short script.

Practical advice

Work on a copy of the folder the first time. Keep the script in version control if you plan to reuse it. Resist the urge to build a graphical interface; a command line script with a clear preview is easier to trust and to maintain.

Frequently Asked Questions

Should I use os.rename or pathlib?

Both work, but pathlib is easier to read and handles paths in a way that works on Windows, macOS and Linux alike. New code usually favours pathlib, and the os module remains fine for older scripts.

How do I undo a bulk rename?

Python has no built-in undo. If you logged each old and new name, you can reverse the list. If you did not, restore from a backup. That is why a dry run and a copy of the folder are worth the small effort.

Can I rename files based on their contents?

Yes. Open the file, read the part you need, such as a title line in a text file or a date in a document, and build the name from it. Keep that logic in its own function so it is easy to test on its own.

Related reading