Python program to delete all files with specific extension in a folder
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 :
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.
The commented numbers in the above program denote the step numbers below :
- 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.
- folder_path is the path of the folder with all files.
- We are looping through the files in the given folder. listdir is used to get one list of all files in a specific folder.
- 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.
- 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.
If you run this program, it will delete all .txt files in the folder. The folder will contain only the below files :
You might also like :
- Python program to rename a directory or file
- Python program to count the total number of lines in a file
- Python tutorial to remove duplicate lines from a text file
- Python 3 program to count the number of blank spaces in a file
- Python program to count the number of words in a file
- List all the files in a Zip file using Python 3