- os.rename() ā the primary way to rename files
- Pattern renaming ā adding prefixes and suffixes
- Batch renaming ā renaming multiple files at once
- Changing extensions ā updating file types
- Error handling ā handling common rename errors
- Best practices ā safe file renaming
Renaming Files in Python
Renaming files is a common task when organizing data, updating file names, or standardizing naming conventions. Python makes it easy to rename files using the os.rename() function from the os module.
Think of renaming a file like updating the label on a folder. The contents stay the same, but the name changes. Python lets you do this programmatically, which is especially useful when you need to rename hundreds of files at once.
š” Key concept: When you rename a file, you're changing its name while keeping the content intact. This is useful for organizing files, fixing naming errors, or standardizing file names across a project.
Using os.rename()
The Primary Way to Rename Files
# First, let's create a file to work with
with open("old_name.txt", "w") as f:
f.write("This is a sample file\n")
f.write("We'll rename this file.")
print(" Created: old_name.txt")
# The os.rename() function takes two arguments:
# 1. The current file name (old name)
# 2. The new file name (new name)
import os
# 1. Basic rename
os.rename("old_name.txt", "new_name.txt")
print(" Renamed: old_name.txt ā new_name.txt")
# 2. Verifying the rename
print("\nš Files in current directory:")
for file in os.listdir("."):
if file.endswith(".txt"):
print(f" {file}")
# 3. Renaming with full paths
# os.rename("data/old_file.txt", "data/new_file.txt")
# 4. Renaming to a different directory
# os.rename("file.txt", "archive/file.txt")
# 5. Renaming a file with spaces
# os.rename("old file.txt", "old_file.txt")
# 6. Using os.path for safer operations
def safe_rename(old_name, new_name):
"""Safely rename a file with path handling"""
import os
try:
os.rename(old_name, new_name)
print(f" Renamed: {old_name} ā {new_name}")
return True
except Exception as e:
print(f" Error: {e}")
return False
# Test the function
safe_rename("new_name.txt", "final_name.txt")
os.rename() key points:
- Two arguments ā old name and new name
- Full paths ā can include directory paths
- Overwrites ā if new name exists, it will be replaced
- Cross-platform ā works on Windows, Linux, macOS
- OS module ā must import os first
Quick Check: What function is used to rename files in Python? (Answer: os.rename())
Renaming with Patterns
Adding Prefixes, Suffixes, and More
# Create sample files first
for i in range(3):
with open(f"sample_{i}.txt", "w") as f:
f.write(f"Sample file {i}")
import os
# 1. Adding a prefix to a file name
def add_prefix(filename, prefix):
"""Add a prefix to a filename"""
new_name = f"{prefix}{filename}"
os.rename(filename, new_name)
print(f"Renamed: {filename} ā {new_name}")
# 2. Adding a suffix
def add_suffix(filename, suffix):
"""Add a suffix to a filename (before extension)"""
name, ext = os.path.splitext(filename)
new_name = f"{name}{suffix}{ext}"
os.rename(filename, new_name)
print(f" Renamed: {filename} ā {new_name}")
# 3. Replacing text in filenames
def replace_in_name(filename, old_text, new_text):
"""Replace text in a filename"""
new_name = filename.replace(old_text, new_text)
os.rename(filename, new_name)
print(f" Renamed: {filename} ā {new_name}")
# 4. Adding a date stamp
import datetime
def add_timestamp(filename):
"""Add a timestamp to a filename"""
name, ext = os.path.splitext(filename)
timestamp = datetime.datetime.now().strftime("%Y%m%d")
new_name = f"{name}_{timestamp}{ext}"
os.rename(filename, new_name)
print(f" Renamed: {filename} ā {new_name}")
# 5. Converting to lowercase
def lowercase_filename(filename):
"""Convert filename to lowercase"""
new_name = filename.lower()
os.rename(filename, new_name)
print(f" Renamed: {filename} ā {new_name}")
# Test the functions with sample files
add_prefix("sample_0.txt", "project_")
add_suffix("sample_1.txt", "_v2")
replace_in_name("sample_2.txt", "sample", "data")
add_timestamp("project_sample_0.txt")
lowercase_filename("project_sample_0_20260808.txt")
Pattern renaming techniques:
- Prefix ā add text at the beginning
- Suffix ā add text before the extension
- Replace ā change specific text in the name
- Timestamp ā add current date/time
- Case changes ā convert to lowercase or uppercase
Quick Check: How would you add a prefix to a filename? (Answer: new_name = prefix + filename)
Batch Renaming Files
Renaming Multiple Files at Once
import os
# Create sample files first
for i in range(5):
with open(f"file_{i}.txt", "w") as f:
f.write(f"This is file {i}")
# 1. Rename all files in a directory
def rename_all_files(directory, prefix=""):
"""Rename all files in a directory with a prefix"""
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
new_name = f"{prefix}{filename}"
os.rename(
os.path.join(directory, filename),
os.path.join(directory, new_name)
)
print(f" Renamed: {filename} ā {new_name}")
rename_all_files(".", "data_")
# 2. Rename files matching a pattern
def rename_matching_files(directory, pattern, new_pattern):
"""Rename files matching a pattern"""
for filename in os.listdir(directory):
if pattern in filename:
new_name = filename.replace(pattern, new_pattern)
os.rename(
os.path.join(directory, filename),
os.path.join(directory, new_name)
)
print(f" Renamed: {filename} ā {new_name}")
rename_matching_files(".", "file", "document")
# 3. Rename files with sequential numbers
def rename_sequential(directory, base_name):
"""Rename files with sequential numbers"""
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for i, filename in enumerate(files, 1):
name, ext = os.path.splitext(filename)
new_name = f"{base_name}_{i:03d}{ext}"
os.rename(
os.path.join(directory, filename),
os.path.join(directory, new_name)
)
print(f" Renamed: {filename} ā {new_name}")
rename_sequential(".", "doc")
# 4. Rename with preview (safe batch rename)
def preview_rename(directory, operation):
"""Preview rename operations before executing"""
changes = []
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
new_name = operation(filename)
changes.append((filename, new_name))
print("š Preview of changes:")
for old, new in changes[:5]:
print(f" {old} ā {new}")
confirm = input("Proceed with rename? (y/n): ")
if confirm.lower() == 'y':
for old, new in changes:
os.rename(
os.path.join(directory, old),
os.path.join(directory, new)
)
print(" Rename complete!")
else:
print(" Canceled.")
# Test preview
preview_rename(".", lambda f: f"preview_{f}")
Batch renaming strategies:
- All files ā rename every file in a directory
- Pattern matching ā rename only files matching a pattern
- Sequential ā add numbers to files in order
- Preview ā show changes before applying
- Filter ā use conditions to select files
Quick Check: Why should you preview batch renames? (Answer: To avoid mistakes when renaming multiple files)
Changing File Extensions
Updating File Types
import os
# Create sample files
for ext in [".txt", ".dat", ".bak"]:
with open(f"data{ext}", "w") as f:
f.write(f"Sample with {ext} extension")
# 1. Change file extension for a single file
def change_extension(filename, new_extension):
"""Change a file's extension"""
name, _ = os.path.splitext(filename)
new_name = f"{name}{new_extension}"
os.rename(filename, new_name)
print(f" Renamed: {filename} ā {new_name}")
change_extension("data.txt", ".csv")
# 2. Change extension for multiple files
def change_all_extensions(directory, old_ext, new_ext):
"""Change extension for all files with a specific extension"""
for filename in os.listdir(directory):
if filename.endswith(old_ext):
name, _ = os.path.splitext(filename)
new_name = f"{name}{new_ext}"
os.rename(
os.path.join(directory, filename),
os.path.join(directory, new_name)
)
print(f" Renamed: {filename} ā {new_name}")
change_all_extensions(".", ".dat", ".json")
# 3. Smart extension change with validation
def safe_extension_change(directory, old_ext, new_ext):
"""Change extension with safety checks"""
for filename in os.listdir(directory):
if filename.endswith(old_ext):
old_path = os.path.join(directory, filename)
name, _ = os.path.splitext(filename)
new_name = f"{name}{new_ext}"
new_path = os.path.join(directory, new_name)
# Check if file already exists
if os.path.exists(new_path):
print(f" Skipping {filename}: {new_name} already exists")
continue
os.rename(old_path, new_path)
print(f" Renamed: {filename} ā {new_name}")
safe_extension_change(".", ".bak", ".backup")
Extension changing key points:
- os.path.splitext() ā splits name and extension
- Check for conflicts ā ensure new name doesn't exist
- Batch changes ā update all files with a specific extension
- Validation ā verify before changing
Quick Check: What function splits a filename into name and extension? (Answer: os.path.splitext())
Error Handling When Renaming
Common Rename Errors and Solutions
import os
# 1. Comprehensive rename function
def safe_rename(old_name, new_name):
"""Safely rename a file with full error handling"""
try:
# Check if old file exists
if not os.path.exists(old_name):
print(f" Error: '{old_name}' does not exist")
return False
# Check if it's a file (not a directory)
if not os.path.isfile(old_name):
print(f" Error: '{old_name}' is not a file")
return False
# Check if new name already exists
if os.path.exists(new_name):
print(f" Error: '{new_name}' already exists")
return False
# Perform the rename
os.rename(old_name, new_name)
print(f" Renamed: {old_name} ā {new_name}")
return True
except PermissionError:
print(f" Permission denied: Cannot rename '{old_name}'")
return False
except OSError as e:
print(f" OS Error: {e}")
return False
except Exception as e:
print(f" Unexpected error: {e}")
return False
# 2. Rename with automatic backup
def rename_with_backup(old_name, new_name):
"""Rename with automatic backup of existing file"""
if os.path.exists(new_name):
backup_name = new_name + ".backup"
os.rename(new_name, backup_name)
print(f" Existing file backed up as: {backup_name}")
return safe_rename(old_name, new_name)
# 3. Rename with user confirmation
def rename_with_confirm(old_name, new_name):
"""Rename with user confirmation"""
print(f" Rename: {old_name} ā {new_name}")
response = input("Confirm? (y/n): ")
if response.lower() == 'y':
return safe_rename(old_name, new_name)
else:
print(" Canceled")
return False
Common rename errors:
- FileNotFoundError ā old file doesn't exist
- FileExistsError ā new name already exists
- PermissionError ā don't have permission
- IsADirectoryError ā trying to rename a directory as file
- Always check ā before attempting rename
Quick Check: What error occurs when you try to rename a file that doesn't exist? (Answer: FileNotFoundError)
Best Practices for Renaming Files
Safe and Professional File Renaming
# Best practices for renaming files
# 1. Always check if files exist
import os
def smart_rename(old_name, new_name):
"""Smart rename with existence checks"""
if not os.path.exists(old_name):
print(f" File not found: {old_name}")
return False
if os.path.exists(new_name):
print(f" File already exists: {new_name}")
response = input("Overwrite? (y/n): ")
if response.lower() != 'y':
print(" Canceled")
return False
try:
os.rename(old_name, new_name)
print(f" Renamed: {old_name} ā {new_name}")
return True
except Exception as e:
print(f" Error: {e}")
return False
# 2. Use path joining for safety
def rename_with_path(directory, old_name, new_name):
"""Rename using full paths"""
old_path = os.path.join(directory, old_name)
new_path = os.path.join(directory, new_name)
return smart_rename(old_path, new_path)
# 3. Test with a dry run first
def dry_run_rename(operations):
"""Perform a dry run before actual rename"""
print(" DRY RUN - No changes will be made:")
for old, new in operations:
print(f" {old} ā {new}")
confirm = input("Proceed with actual rename? (y/n): ")
if confirm.lower() == 'y':
for old, new in operations:
os.rename(old, new)
print(" Rename complete!")
else:
print(" Canceled")
# 4. Use meaningful naming patterns
# Good
# report_2026_08.csv
# user_profile_123.json
# data_backup_2026-08-08.txt
# Bad
# temp.txt
# file1.txt
# new.txt
Best practices summary:
- Check existence ā verify file exists before renaming
- Handle conflicts ā deal with existing files
- Use full paths ā be explicit about file locations
- Test first ā use dry runs for batch operations
- Meaningful names ā use clear naming conventions
Quick Check: What is a dry run? (Answer: Testing rename operations without actually making changes)
Try It Yourself
Experiment with renaming files in the editor below. Try different patterns and operations.
RENAME FILE PRACTICE
========================================
1. CREATING SAMPLE FILES
Created: test_0.txt, test_1.txt, test_2.txt
2. BASIC RENAME
Renamed: test_0.txt ā renamed_0.txt
3. ADDING PREFIX
Renamed: renamed_0.txt ā prefix_renamed_0.txt
4. CHANGING EXTENSION
Renamed: prefix_renamed_0.txt ā prefix_renamed_0.dat
5. BATCH RENAME
Renamed: test_1.txt ā batch_1.txt
Renamed: test_2.txt ā batch_2.txt
6. FINAL FILES
batch_1.txt
batch_2.txt
prefix_renamed_0.dat
Rename file practice complete!
You've Got It!
You now know how to rename files in Python. You understand os.rename(), batch renaming, and how to handle errors professionally.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between os.rename() and shutil.move()?
Can I rename a file to a different directory?
os.rename("file.txt", "archive/file.txt"). This effectively moves the file to the archive directory.
What happens if I try to rename a file that doesn't exist?
FileNotFoundError. Always check if a file exists using os.path.exists() before attempting to rename it.
What's a common interview question about file renaming?
Can I undo a rename operation?
How do I rename files based on their content?
Where to Go From Here
Now that you can rename files, check out these related topics:
Copy File
Learn how to copy files in Python.
Learn More āMove File
Learn how to move files between directories.
Learn More āList Files in Directory
Learn how to list and filter files.
Learn More ā