Delete Files with Specific Extension Python Example

29-Sep-2022

.

Admin

Delete Files with Specific Extension Python Example

Hi Dev,

In this tutorial, I will show you Delete Files with Specific Extension in Python Example. if you have question about python delete all images with specific extension then I will give simple example with solution. I would like to share with you python remove file by extension. We will look at example of python delete 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.

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...

#Python