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

Published by admin on

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 extensionIf 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 :

Categories: python

Leave a Reply

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