Python program to delete all files with specific extension in a folder

Introduction :

In this python programming tutorial, we will learn how to delete all files with a_ specific extension_ in a folder recursively.

We will provide the folder path and file extension to the program and it will delete all files with that provided extension inside the folder.

For this example, we have created one folder called Sample inside the C drive. This folder contains the following files :

python delete all files with specific extension

Using our program, we will remove all files from the folder with_ .txt_ extension. Let’s have a look :

Python program :

#1
import os 
from os import listdir
#2
folder_path = 'C:\Sample\'
#3
for file_name in listdir(folder_path):
    #4
    if file_name.endswith('.txt'):
        #5
        os.remove(folder_path + file_name)

The source code is also available here.

python delete all files with specific extension

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. Import _os _module and _listdir _from the _os _module. _listdir _is required to get the list of all files in a specific folder and _os _module is required to remove a file.

  2. _folder_path _is the path of the folder with all files.

  3. We are looping through the files in the given folder. _listdir _is used to get one list of all files in a specific folder.

  4. endswith is used to check if a file ends with a .txt extension or not. As we are deleting all .txt files in a folder, this_ if condition_ will verify this.

  5. If the file name is ending with .txt extension, we are removing that file using os.remove() function. This function takes the path of the file as parameter. folder_path + file_name is the complete path for the file we are deleting.

python delete files recursively with an extension If you run this program, it will delete all .txt files in the folder. The folder will contain only the below files :

python delete all files with specific extension

You might also like :