Python Delete Files with Specific Extension Example

By Hardik Savani October 30, 2023 Category : Python

Hi,

This post will give you example of python delete files with specific extension. This article will give you simple example of remove files with specific extension python. We will use python delete all images with specific extension. I would like to show you delete all files with extension python. you will do the following things for python remove file by extension.

Sometimes, we need to delete a specific file extension. in this example we will remove only ".png" files from files folder. so let's see below example code.

You can use these examples with python3 (Python 3) version.

let's see below simple example with output:

Example:

main.py

import os
from os import listdir
  
folderPath = 'files/';
    
# Get All List of Files
for fileName in listdir(folderPath):
    #Check file extension
    if fileName.endswith('.png'):
        # Remove File
        os.remove(folderPath + fileName)
  
print("All .png files removed successfully")

Output:

All .png files removed successfully

I hope it can help you...

Tags :
Shares