The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Automatically rename files using patterns

Renaming files automatically using patterns is a common task that can be handled with scripting. Below is a complete guide using Python to rename files in bulk based on customizable patterns. You can adjust the pattern to fit your specific use case such as:

  • Adding a prefix or suffix

  • Changing file extensions

  • Replacing part of the filename

  • Sequential numbering

Example Python Script to Rename Files Using Patterns

python
import os # Directory containing files to rename directory = '/path/to/your/files' # Pattern logic - Example: rename 'image_*.jpg' to 'photo_*.jpg' old_pattern = 'image_' new_pattern = 'photo_' # Optional: use sequential numbering use_sequential_numbering = True file_extension = '.jpg' start_index = 1 # Renaming process for index, filename in enumerate(os.listdir(directory), start=start_index): if old_pattern in filename: old_path = os.path.join(directory, filename) if use_sequential_numbering: new_filename = f'{new_pattern}{index}{file_extension}' else: new_filename = filename.replace(old_pattern, new_pattern) new_path = os.path.join(directory, new_filename) os.rename(old_path, new_path) print(f'Renamed: {filename} -> {new_filename}')

Customization Options

1. Add Prefix or Suffix

python
new_filename = 'prefix_' + filename new_filename = filename.replace('.jpg', '_suffix.jpg')

2. Change File Extension

python
base = os.path.splitext(filename)[0] new_filename = base + '.png'

3. Use Regular Expressions

python
import re pattern = re.compile(r'old(d+).txt') replacement = r'new_1.txt' for filename in os.listdir(directory): match = pattern.match(filename) if match: new_filename = pattern.sub(replacement, filename) os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))

Notes

  • Always back up your files before running bulk rename scripts.

  • You can integrate user input with input() or use command-line arguments with argparse for flexibility.

  • Use os.path.isfile() to avoid renaming folders accidentally.

Let me know if you want this tailored for a specific pattern or system (e.g., Windows batch, Linux shell script).

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About