PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » File Handling » Rename Files in Python

Rename Files in Python

Updated on: April 24, 2022 | 10 Comments

In this tutorial, you will learn how to rename files and folders in Python.

After reading this article, you’ll learn: –

  • Renaming a file with rename() method
  • Renaming files that matches a pattern
  • Renaming all the files in a folder
  • Renaming only the files in a list
  • Renaming and moving a file

Table of contents

  • Steps to Rename File in Python
    • Example: Renaming a file in Python
    • os.rename()
  • Rename a file after checking whether it exists
  • Rename Multiple Files in Python
    • Renaming only a list of files in a folder
  • Renaming files with a timestamp
  • Renaming files with a Pattern
  • Renaming the Extension of the Files
  • Renaming and then moving a file to a new location
  • Practice Problem: Renaming an image file

Steps to Rename File in Python

To rename a file, Please follow these steps:

  1. Find the path of a file to rename

    To rename a file, we need its path. The path is the location of the file on the disk.
    An absolute path contains the complete directory list required to locate the file.
    A relative path contains the current directory and then the file name.

  2. Decide a new name

    Save an old name and a new name in two separate variables.
    old_name = 'details.txt'
    new_name = 'new_details.txt'

  3. Use rename() method of an OS module

    Use the os.rename() method to rename a file in a folder. Pass both the old name and a new name to the os.rename(old_name, new_name) function to rename a file.

Example: Renaming a file in Python

In this example, we are renaming “detail.txt” to “new_details.txt”.

import os

# Absolute path of a file
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"

# Renaming the file
os.rename(old_name, new_name)

Output:

Before rename

Before renaming a file
before renaming a file

After rename

After renaming a file
After renaming a file

os.rename()

As shown in the example, we can rename a file in Python using the rename() method available in the os module. The os module provides functionalities for interacting with the operating systems. This module comes under Python’s standard utility modules.

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

The following are the parameters that we need to pass for the os.rename() method

  • src : Path for the file that has to be renamed
  • dst : A destination path for the newly renamed file
  • src_dir_fd : (Optional) Source file directory
  • dst_dir_fd : (Optional) Destination file directory

Note: If the dst already exists then the FileExistsError will be thrown in Windows and in the case of UNIX an OSError will be thrown.

Rename a file after checking whether it exists

The os.rename() method raises the FileExistsError or OSError when the destination file name already exists. This can be avoided by wrapping our code in the try-except block.

Use the isfile(‘path’) function before renaming a file. It returns true if the destination file already exists.

We can use the following two approaches to continue with renaming by removing the old file or stop without renaming it.

  1. Use os.path.isfile() in an if condition
  2. Write rename code in the try-except block.

Example 1: Use os.path.isfile()

import os

old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"

if os.path.isfile(new_name):
    print("The file already exists")
else:
    # Rename the file
    os.rename(old_name, new_name)

Output

The file already exists

Example 2: The same code could be wrapped in the try-except block as below.

import os

old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"

# enclosing inside try-except
try:
    os.rename(old_name, new_name)
except FileExistsError:
    print("File already Exists")
    print("Removing existing file")
    # skip the below code
    # if you don't' want to forcefully rename
    os.remove(new_name)
    # rename it
    os.rename(old_name, new_name)
    print('Done renaming a file')

Output:

File already Exists
Removing existing file
Done renaming a file

Rename Multiple Files in Python

Sometimes we need to rename all files from a directory. Consider a folder with four files with different names, and we wanted to rename all file names.

We can rename multiple files in a folder using the os.rename() method by following the below steps.

  • Get the list of files in a directory using os.listdir(). It returns a list containing the names of the entries in the given directory.
  • Iterate over the list using a loop to access each file one by one
  • Rename each file

The following example demonstrates how to change the names of all the files from a directory.

import os

folder = r'E:\demos\files\reports\\'
count = 1
# count increase by 1 in each iteration
# iterate all files from a directory
for file_name in os.listdir(folder):
    # Construct old file name
    source = folder + file_name

    # Adding the count to the new file name and extension
    destination = folder + "sales_" + str(count) + ".txt"

    # Renaming the file
    os.rename(source, destination)
    count += 1
print('All Files Renamed')

print('New Names are')
# verify the result
res = os.listdir(folder)
print(res)

Output

All Files Renamed
New Names are
['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
After renaming all files
After renaming all files

Renaming only a list of files in a folder

While renaming files inside a folder, sometimes we may have to rename only a list of files, not all files. The following are the steps we need to follow for renaming only a set of files inside a folder.

  • Providing the list of files that needs to be renamed
  • Iterate through the list of files in the folder containing the files
  • Check if the file is present in the list
  • If present, rename the file according to the desired convention. Else, move to the next file

Example:

import os

files_to_rename = ['sales_1.txt', 'sales_4.txt']
folder = r"E:\demos\files\reports\\"

# Iterate through the folder
for file in os.listdir(folder):
    # Checking if the file is present in the list
    if file in files_to_rename:
        # construct current name using file name and path
        old_name = os.path.join(folder, file)
        # get file name without extension
        only_name = os.path.splitext(file)[0]

        # Adding the new name with extension
        new_base = only_name + '_new' + '.txt'
        # construct full file path
        new_name = os.path.join(folder, new_base)

        # Renaming the file
        os.rename(old_name, new_name)

# verify the result
res = os.listdir(folder)
print(res)

Output

['sales_1_new.txt', 'sales_2.txt', 'sales_3.txt', 'sales_4_new.txt']

Renaming files with a timestamp

In some applications, the data or logs will be stored in the files regularly in a fixed time interval. It is a standard convention to append a timestamp to file name to make them easy for storing and using later. In Python, we can use the datetime module to work with dates and times.

Please follow the below steps to append timestamp to file name:

  • Get the current timestamp using a datetime module and store it in a separate variable
  • Convert timestamp into a string
  • Append timestamp to file name by using the concatenation operator
  • Now, rename a file with a new name using a os.rename()

Consider the following example where we are adding the timestamp in the “%d-%b-%Y” format .

import os
from datetime import datetime

# adding date-time to the file name
current_timestamp = datetime.today().strftime('%d-%b-%Y')
old_name = r"E:\demos\files\reports\sales.txt"
new_name = r"E:\demos\files\reports\sales" + current_timestamp + ".txt"
os.rename(old_name, new_name)

Renaming files with a Pattern

Sometimes we wanted to rename only those files that match a specific pattern. For example, renaming only pdf files or renaming files containing a particular year in their name.

The pattern matching is done using the glob module. The glob module is used to find the files and folders whose names follow a specific pattern.

We can rename files that match a pattern using the following steps: –

  • Write a pattern using wildcard characters
  • Use a glob() method to find the list of files that matches a pattern.
  • Iterate through the files in the folder
  • Change the name according to the new naming convention.

Example: Rename all text files starting with the word “sales” inside the “reports” folder with the new name “revenue” and a counter.

import glob
import os

path = r"E:\demos\files\reports\\"
# search text files starting with the word "sales"
pattern = path + "sales" + "*.txt"

# List of the files that match the pattern
result = glob.glob(pattern)

# Iterating the list with the count
count = 1
for file_name in result:
    old_name = file_name
    new_name = path + 'revenue_' + str(count) + ".txt"
    os.rename(old_name, new_name)
    count = count + 1

# printing all revenue txt files
res = glob.glob(path + "revenue" + "*.txt")
for name in res:
    print(name)

Output

E:\demos\files\reports\revenue_1.txt
E:\demos\files\reports\revenue_2.txt

Renaming the Extension of the Files

We can change only the extension of the files using the rename() method. This is done by getting the list of the files and then get only the file name using the splitext() method of the os module.

This method returns the root and extension separately. Once we get the root/base of the filename, we can add the new extension to it while renaming it using the rename() method

Use the below steps to rename only extension: –

  • Get List file names from a directory using a os.listdir(folder)
  • Next, Iterate each file from a list of filenames
  • Construct current file name using os.path.join() method by passing file name and path
  • Now, use the replace() method of a str class to replace an existing extension with a new extension in the file name
  • At last, use the os.rename() to rename an old name with a new name

Let’s see the example.

import os

folder = r"E:\demos\files\reports\\"
# Listing the files of a folder
print('Before rename')
files = os.listdir(folder)
print(files)

# rename each file one by one
for file_name in files:
    # construct full file path
    old_name = os.path.join(folder, file_name)

    # Changing the extension from txt to pdf
    new_name = old_name.replace('.txt', '.pdf')
    os.rename(old_name, new_name)

# print new names
print('After rename')
print(os.listdir(folder))

Output

Before rename
['expense.txt', 'profit.txt', 'revenue_1.txt', 'revenue_2.txt']
After rename
['expense.pdf', 'profit.pdf', 'revenue_1.pdf', 'revenue_2.pdf']

Renaming and then moving a file to a new location

With the help of the rename() method we can rename a file and then move it to a new location as well. This is done by passing the new location to the rename() method’s dst parameter.

Consider the below example where we are defining two different folders as the source and destination separately. Then using the rename() method, we are changing the name and the location of the file.

Finally when we print the files in the new location we can see the file in the list.

import glob
import os

# Old and new folder locations
old_folder = r"E:\demos\files\reports\\"
new_folder = r"E:\demos\files\new_reports\\"

# Old and new file names
old_name = old_folder + "expense.txt"
new_name = new_folder + "expense.txt"

# Moving the file to the another location

os.rename(old_name, new_name)

Practice Problem: Renaming an image file

We can rename any file in a folder and files of any type using the os.rename(). In the below example we will change the name of an image file inside the folder.

import os
import glob

folder = "/Users/sample/eclipse-workspace/Sample/Files/Images/"
for count, filename in enumerate(os.listdir(folder)):
    oldname = folder + filename   
    newname = folder + "Emp_" + str(count + 1) + ".jpg"
    os.rename(oldname, newname)

# printing the changed names
print(glob.glob(folder + "*.*"))

Output

['/Users/sample/eclipse-workspace/Sample/Files/Images/Emp_2.jpg', '/Users/sample/eclipse-workspace/Sample/Files/Images/Emp_1.jpg'] 

In this article we have covered the basics of renaming a file, the method used for renaming. We also saw how to rename a file with a particular pattern, naming all the files in a folder and adding a date to the file. We also with example how to change the extension of the file and how to move a file to a new location after changing the name.

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python File Handling

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python File Handling
TweetF  sharein  shareP  Pin

Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com