Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Change File Extension in Python



In few scenarios, we need to change the extension of a file programmatically such as renaming a .txt file to .md or converting .csv to .json. Python provides different ways to do this using the os and pathlib modules. In this article, we'll explore how to change a file's extension using both approaches.

Using os.path.splitext()

The os.path.splitext() method of the os module in Python is used to split the file name into the name and extension. We can use this method to strip off the old extension and add the new extension.

Example

In this example, we are using the os.path.splitext() method to change the extension of the given file:

import os

filename = "example.txt"
base = os.path.splitext(filename)[0]
new_filename = base + ".md"

print(new_filename)  # Output: example.md

Here is the output of the above program:

example.md

Using pathlib.Path.with_suffix()

The pathlib module provides a more object-oriented approach, and the method Path.with_suffix() allows us to replace the file's current extension with a new extension easily.

Example

Here is an example using pathlib.Path.with_suffix() method to change the extension of a file:

from pathlib import Path

file = Path("example.md")
new_file = file.with_suffix(".txt")

print(new_file)  # Output: example.txt

Following is the output of the above program:

example.txt

Renaming the file on disk

When we want to change the extension of a file and apply the change to the actual file on our system, we can use the rename() method. This will rename the file and reflect the change in our file directory.

Example

Below is an example where we use the pathlib module to rename a file by changing its extension from .txt to .md:

from pathlib import Path

file = Path("example.txt")
new_file = file.with_suffix(".md")
file.rename(new_file)  # This renames the file on disk

Below is the output of the above program:

The file 'example.txt' has been renamed to 'example.md'

This command changes the file extension and updates the file name in the directory accordingly.

Updated on: 2025-05-15T16:03:31+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements