Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Rename File

Python Rename File - Complete Guide

Learn how to rename files in Python — organize your files efficiently.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Renaming Files in Python
  • Using os.rename()
  • Renaming with Patterns
  • Batch Renaming Files
  • Changing File Extensions
  • Error Handling
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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()

1

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

2

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

3

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

4

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

5

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

6

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. What function is used to rename a file in Python?
2. What happens if you rename a file to a name that already exists?
3. How do you split a filename into name and extension?
4. What is a dry run when renaming files?
5. Which of these is a best practice for renaming files?

Frequently Asked Questions

What is the difference between os.rename() and shutil.move()? ā–¼

os.rename() renames a file within the same directory or moves it to a different directory. shutil.move() is more flexible and can move files across different file systems. For simple renaming, os.rename() is sufficient.

Can I rename a file to a different directory? ā–¼

Yes! os.rename() can move and rename files simultaneously if you provide a full path for the new name: 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? ā–¼

Python will raise a 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? ā–¼

Common questions include: "How do you rename a file in Python?" "What is the difference between os.rename() and shutil.move()?" and "How would you rename multiple files in a directory?"

Can I undo a rename operation? ā–¼

No, renaming is permanent. That's why it's important to use dry runs, backups, and error handling when renaming files, especially in batch operations.

How do I rename files based on their content? ā–¼

First read the file content, extract the information you need, then use that information to construct the new filename. For example, you could read a CSV file and rename it based on a value in the first row.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Write to File Next: Copy File →