Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to 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 splits 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)
The output of the above code is ?
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)
The output of the above code is ?
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
# Create a sample file first
sample_file = Path("example.txt")
sample_file.touch() # Creates the file if it doesn't exist
# Change extension and rename
file = Path("example.txt")
new_file = file.with_suffix(".md")
file.rename(new_file)
print(f"File '{file}' has been renamed to '{new_file}'")
The output of the above code is ?
File 'example.txt' has been renamed to 'example.md'
This command changes the file extension and updates the file name in the directory accordingly.
Comparison
| Method | Module | Renames Actual File? | Best For |
|---|---|---|---|
os.path.splitext() |
os | No | String manipulation |
Path.with_suffix() |
pathlib | No | Object-oriented approach |
Path.rename() |
pathlib | Yes | Actual file renaming |
Conclusion
Use os.path.splitext() for simple string manipulation or pathlib.Path.with_suffix() for object-oriented filename changes. Use rename() when you need to modify the actual file on disk.
