change file extension python

How to Change File Extension of Multiple Files in Python

Python is a great programming language to automate tasks using simple scripts. It provides tons of packages and modules to for this purpose. Sometimes you may need to change file extension of multiple files in Python. In this article, we will learn how to change file extension of multiple files in Python. We will simply rename these files in Python.


How to Change File Extension of Multiple Files in Python

Here are the steps to change file extension of multiple files in Python.

First we import the required modules.

import os, sys

Next, we save the folder location that contains the .txt files whose extension needs to be changed to .csv.

folder = '/home/ubuntu'

Then we loop through the files one by one. We use listdir() function to get a list of all files in the folder.

for filename in os.listdir(folder):
    infilename = os.path.join(folder,filename)
    if not os.path.isfile(infilename): continue
    oldbase = os.path.splitext(filename)
    newname = infilename.replace('.txt', '.csv')
    output = os.rename(infilename, newname)

In the above for loop, we obtain full file path of each file in the folder and store it in variable infilename. We use an if condition to check if the filepath actually exists, else we continue to the next file.

Using os.path.splitext() function, we get the filename without extension and store it in oldbase variable. Then we use replace() function to replace the file extension from .txt to .csv and obtain the new filename. Finally, we use rename() function to rename old filename to new filename.

Here is the full code for your reference. Create a blank python file.

$ vi change_ext.py

Add the following code to it.

#!/usr/bin/env python
import os, sys
folder = '/home/ubuntu'
for filename in os.listdir(folder):
    infilename = os.path.join(folder,filename)
    if not os.path.isfile(infilename): continue
    oldbase = os.path.splitext(filename)
    newname = infilename.replace('.txt', '.csv')
    output = os.rename(infilename, newname)

Save and close the file. Make python file executable.

$ chmod +x change_ext.py

You can run python script using following command.

$ python change_ext.py

In this article, we have learnt how to change file extensions of multiple files in Python.

Also read:

How to Change File Extension of Multiple Files in Linux
How to Remove HTML Tags from CSV File in Python
How to Convert PDF to CSV in Python
How to Convert PDF to Text in Python
How to Convert Text to CSV in Python

Leave a Reply

Your email address will not be published. Required fields are marked *