How to change file extension in Python?


File extensions play a crucial role by helping in identifying the type of content a file holds. The task of changing the file extension is a common in various use cases, such as converting file formats, renaming files for compatibility, or ensuring files are correctly interpreted by specific applications. Python, being a versatile and powerful programming language, offers several methods to change the file extension of a file.

In this informative and enlightening article, we will explore different techniques to change the file extension in Python. We will provide step−by−step explanations and code examples to guide you through the process. Whether you prefer to manipulate file paths using string methods, utilize the "os" module, the "pathlib" module, or third−party libraries, this guide will equip you with the knowledge to effortlessly change file extensions in your Python projects.

Let's embark on this journey of file handling with Python and learn how to change file extensions!

Using String Methods to Change File Extension

One of the simplest ways to change the file extension is by utilizing string methods to manipulate the file name. This method involves splitting the file name based on the existing extension, modifying the extension, and rejoining the name and extension to form the new file name.

Example

  • In the code below, we define the "change_file_extension_with_string_methods()" function, which takes the "filename" and "new_extension" as inputs and returns the new file name with the changed extension.

  • The function first checks if the file name contains a dot (.) to determine if it already has an extension. If it does, we split the name and old extension using "rsplit('.', 1)".

  • The "rsplit('.', 1)" method splits the string at the last occurrence of '.' to handle file names with dots in their names.

  • We then concatenate the name with the "new_extension" and a dot (.) to form the new file name ("new_filename").

  • If the file name does not have an existing extension, we simply concatenate the "new_extension" to the file name to create the new file name.

def change_file_extension_with_string_methods(filename, new_extension):
    if '.' in filename:
        name, old_extension = filename.rsplit('.', 1)
        new_filename = name + '.' + new_extension
    else:
        new_filename = filename + '.' + new_extension
    return new_filename

Using the os.path Module to Change File Extension

The "os.path" module provides a cross−platform way to handle file paths in Python. We can use this module to manipulate file names and change their extensions.

Example

  • In this example, we import the "os" module, which provides functions for interacting with the operating system, including file and directory operations.

  • The "change_file_extension_with_os_path()" function takes the "filename" and "new_extension" as inputs and returns the new file name with the changed extension.

  • We use "os.path.splitext(filename)" to split the file name into the base name (name without the extension) and the extension.

  • The "os.path.splitext()" function returns a tuple containing the base name and the extension of the given file name.

  • We then concatenate the base name with the "new_extension" and a dot (.) to form the new file name ("new_filename").

import os

def change_file_extension_with_os_path(filename, new_extension):
    base_name = os.path.splitext(filename)[0]
    new_filename = base_name + '.' + new_extension
    return new_filename

Using the pathlib Module to Change File Extension

The "pathlib" module provides an object−oriented approach to handle file paths in Python. We can leverage the "Path" class to manipulate file names and change their extensions.

Example

  • In this example, we import the "Path" class from the "pathlib" module, which represents a file system path.

  • The "change_file_extension_with_pathlib()" function takes the "filename" and "new_extension" as inputs and returns the new file name with the changed extension.

  • We create a "Path" object with "Path(filename)" to represent the input file name.

  • We use the "with_suffix()" method of the "Path" object to change the extension to the "new_extension".

  • The "with_suffix()" method returns a new "Path" object with the updated extension, and we store it in the "new_filename" variable.

from pathlib import Path

def change_file_extension_with_pathlib(filename, new_extension):
    path_object = Path(filename)
    new_filename = path_object.with_suffix('.' + new_extension)
    return new_filename

Using the shutil Module to Change File Extension

The "shutil" module in Python provides high−level file operations. While its primary purpose is to handle file copying and removal, it can also be used to change file extensions.

Example

  • In this example, we import the "shutil" module, which provides functions for high−level file operations.

  • The "change_file_extension_with_shutil()" function takes the "src_filename" (file with the current extension) and "dst_filename" (file with the desired extension) as inputs and changes the extension of the file by renaming it.

  • We use "shutil.move(src_filename, dst_filename)" to move the file from "src_filename" to "dst_filename".

  • The "shutil.move()" function effectively renames the file and changes its extension in the process.

import shutil

def change_file_extension_with_shutil(src_filename, dst_filename):
    shutil.move(src_filename, dst_filename)

Using the pyrenamer Library to Change File Extension

If you want to rename files with a new extension, you can achieve this without any external libraries using the built−in os module. Here's an example of how you can change the file extension using the os.rename function:

We use the os.path.isfile() function to check if the file with the given filename exists. Then we construct the new filename with the desired new_extension using os.path.splitext(). Finally, we use os.rename() to perform the renaming operation.

import os

def change_file_extension(filename, new_extension):
    # Check if the file exists before renaming
    if os.path.isfile(filename):
        file_name, old_extension = os.path.splitext(filename)
        new_filename = file_name + '.' + new_extension
        try:
            os.rename(filename, new_filename)
            print(f"File '{filename}' renamed to '{new_filename}' with new extension.")
        except Exception as e:
            print(f"Error occurred while renaming the file: {e}")
    else:
        print(f"File '{filename}' not found.")

# Example usage
filename = 'example.txt'
new_extension = 'pdf'
change_file_extension(filename, new_extension)

Output

File 'example.txt' not found.

Changing the file extension is a routine task in file handling and manipulation. In this article, we explored various methods to change file extensions in Python. We learned how to manipulate file names using string methods, leverage the "os.path" and "pathlib" modules, utilize the "shutil" module for high−level file operations, and use the "os.rename" function for batch renaming tasks.

With this knowledge in hand, you can confidently change file extensions in your Python projects, whether you are working with a single file or processing files in bulk.

Updated on: 11-Sep-2023

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements