DEV Community

luck
luck

Posted on

Bulk Rename Files from the Command Line with Python

Bulk Rename Files from the Command Line with Python

Renaming hundreds of files manually is tedious. Here is how to do it with a simple Python script.

The Problem

You have a folder full of photos and you need to add prefixes, change extensions, or convert case.

Quick Solution

import os, sys

def rename_files(directory, prefix=""):
    for f in os.listdir(directory):
        fp = os.path.join(directory, f)
        if not os.path.isfile(fp): continue
        name, ext = os.path.splitext(f)
        new_path = os.path.join(directory, prefix + name + ext)
        print(f"{f} -> {os.path.basename(new_path)}")

if __name__ == "__main__":
    rename_files(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "")
Enter fullscreen mode Exit fullscreen mode
python renamer.py ./photos vacation_
Enter fullscreen mode Exit fullscreen mode

This adds a prefix to every file in the directory.

Advanced Features

The full CLI tool (Bulk Renamer Pro) adds:

  • Regex find-and-replace
  • Case conversion
  • Auto-numbering
  • Extension filtering
  • Recursive scanning
  • Safe dry-run mode

Why CLI?

  • Fast: one command, hundreds of files
  • Repeatable: same result every time
  • Scriptable: chain with other commands

Built with Python 3. No external dependencies.

Top comments (0)