Fundamentals 6 min read

Three Python 3 Methods for Bulk File Renaming

This article introduces three Python 3 techniques for bulk file renaming—recursive numbering, renaming based on creation timestamps, and using regular expressions—explaining their advantages, providing complete code examples, and guiding readers on adapting the scripts for their own file management needs.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Three Python 3 Methods for Bulk File Renaming

Large-scale file renaming is a common task, especially when sorting and numbering thousands or millions of files. This article discusses three Python 3 approaches to make file names more descriptive or standardized.

1. Rename to recursively numbered files

import os
path = '/path/to/folder'
files = os.listdir(path)
for i, file in enumerate(sorted(files)):
    ext = os.path.splitext(file)[1]
    os.rename(os.path.join(path, file), os.path.join(path, f'{i+1:04d}{ext}'))

Replace path with the target folder. The script enumerates files in sorted order and renames them using a zero‑padded four‑digit sequence.

2. Rename based on file creation time

import os
import time
path = '/path/to/folder'
files = os.listdir(path)
for file in files:
    file_path = os.path.join(path, file)
    creation_time = os.path.getctime(file_path)
    formatted_time = time.strftime('%Y%m%d_%H%M%S', time.localtime(creation_time))
    new_file_name = f'{formatted_time}{os.path.splitext(file_path)[1]}'
    os.rename(file_path, os.path.join(path, new_file_name))

This script obtains each file’s creation timestamp, formats it as YYYYMMDD_HHMMSS , and renames the file accordingly.

3. Rename using regular expressions

import os
import re
path = '/path/to/folder'
files = os.listdir(path)
pattern = re.compile(r'\d{3,4}')
for file in files:
    file_path = os.path.join(path, file)
    match = re.search(pattern, file)
    if match:
        new_file_name = f'{match.group(0)}{os.path.splitext(file_path)[1]}'
        os.rename(file_path, os.path.join(path, new_file_name))

This method extracts numeric patterns from existing file names with a regex and uses the captured digits as the new name, offering flexibility at the cost of more setup.

Each approach has its own strengths: sequential numbering is simple and sortable, timestamp‑based naming embeds useful metadata, and regex‑based renaming provides the most flexibility for custom patterns.

Pythonscriptingregular expressionsBulk Processingfile-renaming
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.