Python 3 Shutil Library Script to Remove All Files and SubDirectories Inside a Folder or Directory Full Project For Beginners

Python 3 Shutil Library Script to Remove All Files and SubDirectories Inside a Folder or Directory Full Project For Beginners

 

Welcome folks today in this blog post we will be removing all files and subdirectories inside a folder or directory in python using shutil library. 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, shutil
folder = 'uploads'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))

 

See also  Python 3 Tkinter Font Chooser Popup Window Using askfont Widget GUI Desktop App Full Project For Beginners

So here we are importing the built in modules such as os and shutil and then we are providing the path of the directory which is uploads and then we are deleting all the files and subdirectories inside this uploads folder as shown below

 

 

So as you can see we have four files and one directory inside this directory. So now if you execute this python script by typing the below command as shown below

 

python app.py

 

 

So as you can see now the directory is empty and all the files and subdirectories were deleted automatically by using this python script

Leave a Reply