How to rename a file in Python

Learn how to rename files in Python. This guide covers various methods, tips, real-world applications, and how to debug common errors.

How to rename a file in Python
Published on: 
Tue
Feb 24, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

Renaming files in Python is a common task for data organization and project management. Python’s built-in os module provides simple functions, like os.rename(), to handle this process efficiently.

In this article, we'll explore several techniques for file renaming, from basic to advanced. You'll find practical tips, see real-world applications, and get debugging advice to help you confidently manage files in your Python projects.

Using os.rename() for basic file renaming

import os
# Rename a file from old_name.txt to new_name.txt
os.rename('old_name.txt', 'new_name.txt')
print("File renamed successfully!")--OUTPUT--File renamed successfully!

The os.rename() function is a direct command to the operating system to change a file's name. It's a core part of the os module, which handles interactions between your Python script and the file system. The function is memory-efficient because it doesn't move or copy data; it simply updates the file's metadata entry in the directory.

It requires two arguments: the current file path and the new file path. For example, os.rename('old_name.txt', 'new_name.txt') tells Python to find old_name.txt in the current directory and rename it.

Core file renaming techniques

While os.rename() is a great starting point, Python also provides more robust tools like shutil.move(), pathlib.Path, and os.replace() for handling complex renaming scenarios.

Using shutil.move() to rename files

import shutil
# shutil.move can both move and rename files
shutil.move('original.txt', 'renamed.txt')
print("File renamed with shutil.move")--OUTPUT--File renamed with shutil.move

The shutil.move() function from Python's shutil module is more versatile than os.rename(). While it can simply rename a file in the same directory, its main advantage is handling both renaming and moving files in one step.

  • It can move a file to a new directory and rename it at the same time.
  • If the destination is on a different file system, it safely copies the file and then removes the original.

This makes shutil.move() a more robust option for complex file management tasks.

Renaming with pathlib.Path

from pathlib import Path
file_path = Path('current_name.txt')
file_path.rename('new_name.txt')
print(f"Renamed {file_path} to new_name.txt")--OUTPUT--Renamed current_name.txt to new_name.txt

The pathlib module offers a modern, object-oriented way to handle file system paths. Instead of treating paths as simple strings, you create a Path object that represents the file. You can then call methods like rename() directly on that object, making your code more intuitive.

  • This approach improves readability by bundling path-related data and operations together.
  • It helps you write cleaner, more expressive code that is easier to maintain.

Using pathlib.Path is often preferred in modern Python because it makes file system interactions feel more natural and less error-prone.

Safely rename with os.replace()

import os
# os.replace atomically replaces the destination if it exists
os.replace('source.txt', 'destination.txt')
print("File replaced safely using atomic operation")--OUTPUT--File replaced safely using atomic operation

The os.replace() function is your safest bet for renaming when the destination file might already exist. Unlike os.rename(), which can fail on some operating systems if the new name is taken, os.replace() will atomically overwrite the destination. This means the operation is guaranteed to complete successfully without leaving your files in an inconsistent state.

  • It's ideal for tasks where you need to update a file by renaming a temporary one to its final name.
  • This prevents errors from partially completed renames, ensuring data integrity.

Advanced file renaming strategies

For more complex jobs, you can combine these core techniques to perform batch renames, match patterns with re, or safely swap file names.

Batch renaming multiple files

import os
for i, filename in enumerate(os.listdir('.')):
if filename.endswith('.txt'):
new_name = f"file_{i}.txt"
os.rename(filename, new_name)
print(f"Renamed {filename} to {new_name}")--OUTPUT--Renamed old_file.txt to file_0.txt
Renamed another_file.txt to file_1.txt
Renamed important_doc.txt to file_2.txt

Batch renaming is perfect for organizing large sets of files. This script loops through every item in the current directory using os.listdir('.'). The enumerate() function provides a counter, which helps create unique, sequential file names for each match.

  • The code first identifies files ending with the .txt extension.
  • For each match, it generates a new name like file_0.txt using an f-string.
  • Finally, os.rename() applies the new name, automating what would otherwise be a tedious manual task.

Pattern-based renaming with re

import os
import re
pattern = re.compile(r'data_(\d+)\.csv')
for filename in os.listdir('.'):
match = pattern.match(filename)
if match:
new_name = f"processed_{match.group(1)}.csv"
os.rename(filename, new_name)
print(f"Renamed {filename} to {new_name}")--OUTPUT--Renamed data_001.csv to processed_001.csv
Renamed data_002.csv to processed_002.csv
Renamed data_003.csv to processed_003.csv

When you need more than a simple text match, Python's re module lets you use regular expressions for powerful pattern-based renaming. This approach is perfect for restructuring filenames that follow a consistent format. The code uses re.compile() to create a reusable pattern that finds specific files.

  • The pattern r'data_(\d+)\.csv' targets files like data_001.csv.
  • By using match.group(1), you can extract the captured digits from the original filename and insert them into the new one, creating names like processed_001.csv.

Using a temporary name for safe swapping

import os
import uuid

def safe_rename(old_name, new_name):
temp_name = f"temp_{uuid.uuid4()}"
os.rename(new_name, temp_name) if os.path.exists(new_name) else None
os.rename(old_name, new_name)
os.rename(temp_name, old_name) if os.path.exists(temp_name) else None

safe_rename('file1.txt', 'file2.txt')--OUTPUT--# No output, but file1.txt and file2.txt are swapped safely

Swapping two filenames, like file1.txt and file2.txt, isn't straightforward since a direct rename can cause errors or overwrite data. This function safely handles the swap by using a temporary placeholder, ensuring no information is lost.

  • It starts by generating a unique temporary name with uuid.uuid4() to prevent any conflicts during the operation.
  • The destination file (new_name) is moved to this temporary name, which clears the way for the next step.
  • Finally, the source file (old_name) takes the destination's place, and the temporary file is renamed to the source's original name, completing the swap.

Move faster with Replit

Replit is an AI-powered development platform where you can skip setup and start coding instantly. It comes with all Python dependencies pre-installed, so you don't have to worry about environment configuration. This allows you to move from learning individual techniques to building complete applications faster with Agent 4.

Instead of piecing together functions, you can describe the tool you need and let it handle the development. For example, you could build:

  • A media organizer that renames image files based on their creation date to keep your library tidy.
  • A data cleanup utility that standardizes report filenames, changing names like report-04-2024.csv to 2024-04_report.csv.
  • A versioning script that safely swaps draft.txt and final.txt filenames while archiving the old final version.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with the right tools, renaming files can lead to errors, but most issues are straightforward to diagnose and resolve.

Handling "File not found" errors with os.rename()

A FileNotFoundError is one of the most common issues with os.rename(), typically caused by a typo in the path or filename. To avoid this, you can:

  • Check if the file exists with os.path.exists() before trying to rename it.
  • Wrap the operation in a try...except FileNotFoundError: block to catch the error gracefully without crashing your script.

Fixing permission errors when renaming across directories

You'll see a PermissionError when your script lacks the authority to modify a file. This often happens when working with protected system directories or across different user accounts. The operating system is just preventing unauthorized changes, so you'll need to ensure the script has the necessary write permissions for both the source and destination.

Dealing with FileExistsError when the destination already exists

A FileExistsError arises when the destination filename already exists, as os.rename() won't overwrite files on some systems like Windows. Your options are:

  • Use os.replace() if you intend to overwrite the destination file. It’s designed for this and performs the action safely.
  • Check for the file with os.path.exists() first if you want to avoid overwriting, allowing you to choose a different name.

Handling "File not found" errors with os.rename()

The FileNotFoundError is a classic stumbling block. It'll pop up when os.rename() can't locate the source file, usually due to a typo or running the script from the wrong directory. The code below shows how this error can crash your program.

import os
# This will raise FileNotFoundError if old_file.txt doesn't exist
os.rename('old_file.txt', 'new_file.txt')
print("File renamed successfully!")

This code fails because it assumes old_file.txt exists. When the file is missing, the script has no instructions for handling the error and crashes. The next snippet shows how to manage this gracefully.

import os
# Check if file exists before attempting to rename
if os.path.isfile('old_file.txt'):
os.rename('old_file.txt', 'new_file.txt')
print("File renamed successfully!")
else:
print("Error: The file old_file.txt does not exist")

This solution prevents the script from crashing by first checking if the file exists. The os.path.isfile() function returns True only if the file is present, allowing the os.rename() operation to proceed safely. An if...else block provides a clear path for both success and failure, printing a helpful error message instead of raising an exception. This is crucial when dealing with files that might be moved or deleted by other processes.

Fixing permission errors when renaming across directories

You'll encounter a PermissionError not just from locked files, but also when trying to move a file across different drives. The os.rename() function typically works only within the same file system, making cross-drive operations fail. The following code illustrates this scenario.

import os
# This might raise a PermissionError when crossing drive boundaries
os.rename('C:/docs/report.txt', 'D:/backup/report.txt')
print("File moved and renamed successfully!")

This code triggers an error because os.rename() is only designed for simple metadata changes within the same file system. It cannot perform the copy-and-delete operation needed to move a file across drives. See a better approach below.

import shutil
try:
# Use shutil.move() to handle cross-directory operations
shutil.move('C:/docs/report.txt', 'D:/backup/report.txt')
print("File moved and renamed successfully!")
except PermissionError:
print("Error: Permission denied. Check file and directory permissions.")

This solution uses shutil.move() because it’s designed to move files across different drives, like from C: to D:. While os.rename() often fails in this scenario, shutil.move() handles it by copying the file to the new location and then deleting the original. This makes it the go-to for robust cross-directory operations. The try...except block gracefully handles any genuine PermissionError if you lack write access to the destination.

Dealing with FileExistsError when the destination already exists

The FileExistsError occurs when os.rename() tries to use a filename that's already taken. On systems like Windows, this function won't overwrite an existing file by default, which is a safety feature to prevent accidental data loss.

The code below demonstrates how this can cause your script to fail unexpectedly. It attempts a simple rename operation where the destination file already exists, triggering the error and halting the program.

import os
# This will raise FileExistsError on some systems if new_name.txt already exists
os.rename('old_name.txt', 'new_name.txt')
print("File renamed successfully!")

This script attempts a direct rename without checking if the destination file is already in use. Since os.rename() won't overwrite existing files on some systems, this oversight triggers a FileExistsError. The code below shows a better approach.

import os
import errno

try:
os.rename('old_name.txt', 'new_name.txt')
print("File renamed successfully!")
except OSError as e:
if e.errno == errno.EEXIST:
print("Error: Destination file already exists")
# Either remove the destination or use a different approach
# os.replace('old_name.txt', 'new_name.txt') # Overwrites destination
else:
raise

This solution uses a try...except OSError block to gracefully handle the error. It checks if the error number, e.errno, matches errno.EEXIST, which specifically confirms the destination file already exists. This lets your script print a clear message instead of crashing. If you actually intend to overwrite the file, using os.replace() is a safer and more direct approach. This method gives you precise control over how your script behaves when encountering existing files.

Real-world applications

With error handling mastered, you can confidently apply these renaming techniques to practical tasks like organizing photos or versioning documents through vibe coding.

Organizing photos by modification date using os.path

You can easily organize a messy photo collection by renaming each file based on its modification date, which you can retrieve using os.path.getmtime().

import os
from datetime import datetime

# Rename a photo based on its modification time
photo = 'vacation.jpg'
mod_time = os.path.getmtime(photo)
date_str = datetime.fromtimestamp(mod_time).strftime('%Y%m%d')
new_name = f"photo_{date_str}{os.path.splitext(photo)[1]}"
os.rename(photo, new_name)
print(f"Renamed {photo} to {new_name}")

This script renames a photo using its modification date, making your files easy to sort. It works by first getting the file's metadata.

  • The os.path.getmtime() function retrieves the last modification time as a Unix timestamp.
  • datetime.fromtimestamp() converts this into a date object, which is then formatted into a YYYYMMDD string.
  • os.path.splitext() cleverly extracts the original file extension, ensuring the file type remains unchanged.

An f-string then pieces everything together before os.rename() executes the change.

Creating a simple document versioning system

By renaming a document with a timestamp using os.rename(), you can create a simple versioning system that archives the current file before it’s updated.

import os
from datetime import datetime

# Create a versioned backup by renaming
document = 'report.txt'
timestamp = datetime.now().strftime('%Y%m%d')
new_name = f"{document.split('.')[0]}_v{timestamp}.txt"
os.rename(document, new_name)
print(f"Renamed {document} to {new_name}")

This script demonstrates how to create a dated snapshot of a document, a practical way to preserve a version of a file before you modify it.

  • The code first generates a timestamp from the current date using datetime.now().
  • It then isolates the base filename from its extension by using the split('.') method.
  • An f-string assembles a new versioned name, such as report_v20240521.txt, before os.rename() applies the change, creating a backup with a clear, chronological label.

Get started with Replit

Now, turn these techniques into a real tool with Replit Agent. Try prompts like, “Build a script to rename photos by date” or “Create a utility to standardize CSV filenames.”

The Agent writes the code, tests for errors, and deploys the app for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.