Python 3 Glob Module Script to Remove all Files in a Directory or SubDirectory With a Specific Extension Using Pattern Matching Full Project For Beginners

Python 3 Glob Module Script to Remove all Files in a Directory or SubDirectory With a Specific Extension Using Pattern Matching Full Project For Beginners

 

Welcome folks today in this blog post we will be removing all files with a specific extension in directory or subdirectory using glob module in python. All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

app.py

 

import os
import glob

files = glob.iglob('uploads/**/*.csv', recursive=True)

for f in files:
    try:
        os.remove(f)
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

 

 

Now as you can see inside my directory uploads we have lots of different extensions files and subdirectorytemp which contains different extensions files as shown below

See also  Python 3 Script to Perform Remote Commands Over SSH Client Protocol on Command Line Automatically Full Project For Beginners

 

 

So here in the above script we are only matching the .csv files and deleting it so if you execute this script by typing the below command as shown below

 

python app.py

 

 

So as you can see all the .csv files were deleted inside root directory and also subdirectory also using this python script

Leave a Reply