Skip to content

Instantly share code, notes, and snippets.

@robes7
Last active July 15, 2025 16:25
Show Gist options
  • Select an option

  • Save robes7/20514cdfbba26a4fc746b491080bd54c to your computer and use it in GitHub Desktop.

Select an option

Save robes7/20514cdfbba26a4fc746b491080bd54c to your computer and use it in GitHub Desktop.
Bulk file renamer
# Python script for bulk renaming files in a specified directory
# How to use:
# python bulk_renamer.py /path/to/directory new_name_prefix --extension .txt --start 1
# Renames .txt files as new_name_prefix1.txt, new_name_prefix2.txt, etc.
# If --extension is omitted, it renames all files.
# Modify the prefix to customize filenames.
import os
import argparse
def bulk_rename(directory, prefix, extension=None, start_number=1):
"""Renames files in a given directory with a specified prefix and optional extension filter."""
files = sorted(os.listdir(directory)) # Sort to maintain order
count = start_number
for file in files:
file_path = os.path.join(directory, file)
if not os.path.isfile(file_path):
continue # Skip directories
file_ext = os.path.splitext(file)[1]
if extension and file_ext.lower() != extension.lower():
continue # Skip files not matching extension
new_name = f"{prefix}{count}{file_ext}"
new_path = os.path.join(directory, new_name)
os.rename(file_path, new_path)
print(f"Renamed: {file} -> {new_name}")
count += 1
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Bulk rename files in a directory.")
parser.add_argument("directory", type=str, help="Path to the directory containing files.")
parser.add_argument("prefix", type=str, help="New filename prefix.")
parser.add_argument("--extension", type=str, help="Only rename files with this extension (e.g., .txt).", default=None)
parser.add_argument("--start", type=int, help="Starting number for renaming.", default=1)
args = parser.parse_args()
bulk_rename(args.directory, args.prefix, args.extension, args.start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment