In this article, you will learn how to change file extension in Python.
Changing File Extension
You can change the file extension in Python by manipulating the file name string using Python’s built-in string methods. Here’s an example of how to change the extension of a file from “.txt” to “.csv”:
import os # Get the current file name and directory current_file_path = "/path/to/current/file.txt" file_dir = os.path.dirname(current_file_path) file_name = os.path.basename(current_file_path) # Replace the ".txt" extension with ".csv" new_file_name = os.path.splitext(file_name) + ".csv" # Create the new file path new_file_path = os.path.join(file_dir, new_file_name) # Rename the file os.rename(current_file_path, new_file_path)
In this example, we first import the “os” module to work with the file system. Then, we get the current file name and directory using the “os.path.dirname” and “os.path.basename” functions. Next, we use the “os.path.splitext” function to split the file name into its base name and extension, and replace the extension with “.csv”. Finally, we use the “os.path.join” function to create the new file path by combining the directory and new file name, and then use the “os.rename” function to rename the file.