Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to rename multiple files recursively using Python?
The act of renaming multiple files recursively in Python can be a useful task when it is required to change the names of multiple files within a directory and its subdirectories. If you need to replace certain characters, add prefixes or suffixes, or completely change the file names, Python has powerful tools to accomplish such operations. In this article, we explore different approaches to renaming multiple files recursively using Python ?
Using os.walk() to Traverse the Directory Tree
The os.walk() function from the os module is used to traverse the directory tree and access files and directories within it. We utilize this function to iterate over all the files in a directory and its subdirectories and perform the renaming operation ?
Example − Replace Text in Filenames
import os
def rename_files_recursively(directory, old_name, new_name):
for root, dirs, files in os.walk(directory):
for file in files:
if old_name in file:
file_path = os.path.join(root, file)
new_file_path = os.path.join(root, file.replace(old_name, new_name))
os.rename(file_path, new_file_path)
print(f"Renamed: {file} to {file.replace(old_name, new_name)}")
# Example usage (create test files first)
os.makedirs('test_dir/subdir', exist_ok=True)
open('test_dir/old_file1.txt', 'w').close()
open('test_dir/subdir/old_file2.txt', 'w').close()
rename_files_recursively('test_dir', 'old_', 'new_')
The output shows the renamed files ?
Renamed: old_file1.txt to new_file1.txt Renamed: old_file2.txt to new_file2.txt
Example − Add Prefix to All Files
import os
def add_prefix_recursively(folder_path, new_prefix):
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
file_dir, file_name = os.path.split(file_path)
new_name = new_prefix + file_name
new_path = os.path.join(file_dir, new_name)
os.rename(file_path, new_path)
print(f"Renamed: {file_name} to {new_name}")
# Example usage (create test files first)
os.makedirs('prefix_test', exist_ok=True)
open('prefix_test/file1.txt', 'w').close()
open('prefix_test/file2.txt', 'w').close()
add_prefix_recursively('prefix_test', 'backup_')
Renamed: file1.txt to backup_file1.txt Renamed: file2.txt to backup_file2.txt
Using pathlib.Path for Modern File Operations
Another approach is using the pathlib module, which provides a more modern and object−oriented way to handle file paths. The rglob() method performs a recursive search ?
Example
from pathlib import Path
def rename_files_with_pathlib(directory, old_name, new_name):
path = Path(directory)
for file_path in path.rglob('*'):
if file_path.is_file() and old_name in file_path.name:
new_file_path = file_path.with_name(file_path.name.replace(old_name, new_name))
file_path.rename(new_file_path)
print(f"Renamed: {file_path.name} to {new_file_path.name}")
# Example usage (create test files first)
Path('pathlib_test/subdir').mkdir(parents=True, exist_ok=True)
Path('pathlib_test/temp_file1.txt').touch()
Path('pathlib_test/subdir/temp_file2.txt').touch()
rename_files_with_pathlib('pathlib_test', 'temp_', 'final_')
Renamed: temp_file1.txt to final_file1.txt Renamed: temp_file2.txt to final_file2.txt
Renaming Files by Extension
You can also rename files based on their extensions or specific patterns ?
import os
def rename_by_extension(directory, extension, new_prefix):
count = 1
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(extension):
file_path = os.path.join(root, file)
file_name, file_ext = os.path.splitext(file)
new_name = f"{new_prefix}_{count:03d}{file_ext}"
new_path = os.path.join(root, new_name)
os.rename(file_path, new_path)
print(f"Renamed: {file} to {new_name}")
count += 1
# Example usage (create test files first)
os.makedirs('ext_test', exist_ok=True)
open('ext_test/document1.txt', 'w').close()
open('ext_test/document2.txt', 'w').close()
open('ext_test/image.jpg', 'w').close()
rename_by_extension('ext_test', '.txt', 'doc')
Renamed: document1.txt to doc_001.txt Renamed: document2.txt to doc_002.txt
Comparison of Methods
| Method | Module | Best For | Performance |
|---|---|---|---|
os.walk() |
os | Simple text replacement | Good |
pathlib.Path |
pathlib | Modern Python code | Good |
| Extension−based | os | Organizing by file type | Good |
Conclusion
Python provides multiple approaches for renaming files recursively. Use os.walk() for simple operations and pathlib for modern, object−oriented code. Always test your renaming logic on a backup directory first to avoid accidental data loss.
