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 :
#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.
- folderpath _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. folderpath + filename 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 :
- 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