Python – Replace File Extension
To replace the file extension with a new extension in Python, you can use os module, get the root of the file, and then concatenate the new extension.
In this tutorial, we will see how to replace the file extension with a new extension, with a step by step process, and examples.
Steps to replace the file extension in Python
- Given filename or complete file path in the variable filename.
- Given new file extension in variable new_extension.
- Import os module at the beginning of the program.
- Call os.path.splitext() method and pass the given filename as argument. The method returns a tuple, where the first part is the root of the file (filename or file path without extension), and the second part is the file extension. Store them in root, and file_extension respectively.
- We need the root part in the above step. Concatenate the root and new_extension. The resulting string is the required string.
Program
The complete program to replace the extension in filename with a new extension is given below. We are replacing the old extension with a new extension of .csv.
Python Program
import os
# Given string
filename = "/path/to/something.txt"
# Required new file extension
new_extension = ".csv"
# Get root and extension of given file
root, extension = os.path.splitext(filename)
# Replace extension
new_filename = root + new_extension
print(new_filename)
CopyOutput
/path/to/something.csv
Summary
In this tutorial, we learned how to replace the file extension with a new extension in a filename, with step by step process and example programs.