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
1 2 3 4 5 6 7 8 9 10 11 |
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)) |
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