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 :

The source-code for the below program is 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 :

Leave a Reply