Imagine having a bulk load of files in directories, specific extension files, or only directories that need to be deleted. This tedious task is made easy by python by providing us with modules like os
and shutil
.These modules can delete the target directory or files by just inputting the address and required extension.
These modules provide various options, such as selecting only directory content or the entire directory.
Overview of modules
In this article, we will be implementing os and shutil modules which are the most common modules used in Python to perform files and directory operations. Let’s have an overview of them before we dive into the implementation.
os
module: To connect with the operating system and carry out tasks like creating, renaming, and removing files and directories, we use the os module.
Below are a few commonly used functions ofos
module:os.rename(src, dst)
: Renames the src file to dst file.os.remove(path)
: Deletes the file at the given address.os.mkdir(path)
: Creates a new directory at the given address.os.listdir(path)
: Returns a list of all files and directories in the directory at the given address.- the
shutil
module, on the other hand, provides a higher-level interface for file operations. To copy, move and delete files and directories are a few functions provided by this module.
Below are a few commonly used functions ofshutil
module:shutil.copy(src, dst)
: Copies the file from src to dst.shutil.move(src, dst)
: Moves the file from src to dst.shutil.rmtree(path)
: Deletes the directory and all its contents at the given address.
Code Implementation for Deleting the Contents of a Folder
In Python, you can delete the contents of a folder using the ‘os’ and ‘shutil’ modules. The ‘os’ module allows you to perform file and directory operations, while the ‘shutil’ module provides a higher-level interface for file operations. With these modules, you can delete entire directories, specific files, or files with a certain extension.
Let’s now get right into the different ways we can delete the contents of a folder using Python.
Example 1: Deleting Only Files, Not Directories
import os
folder_path = r"C:/Users/Ashu/Desktop/Folder1" #enter path here
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
os.rmdir(file_path)
except Exception as e:
print(f"Error deleting {file_path}: {e}")
print("Deletion done")
We begin by importing os
library. folder_path stores the address of the folder we want to delete, to iterate over the files in the folder we define a for loop. The file path is stored in the file_path variable if the file is a regular file, we delete it using an if statement, if the file is a directory we execute elif, and if there is an exception ‘Error deleting {file_path}’ message is displayed.
About folder


Output:


Example 2: Deleting Directories Using shutil
import shutil
folder_path =r"C:/Users/Ashu/Desktop/Folder1" # enter your path
shutil.rmtree(folder_path)
print("Deletion done")
shutil module provides a higher-level interface for file operations than built-in os module. We define the folder path in shutil.rmtree()
, this function enables us to delete a directory and its content itit is similar to os.rmdir(), but unlike os.rmdir(), shutil.rmtree() can remove non-empty directories.
About folder


This code will delete the entire folder with its content.
Output:


Example 3: Deleting Files with a Specific Extension
import os
folder_path =r"C:/Users/Ashu/Desktop/Folder" # enter path here
extension = ".txt" # set the file extension to delete
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path) and filename.endswith(extension):
os.remove(file_path)
except Exception as e:
print(f"Error deleting {file_path}: {e}")
print("Deletion done")
The directory we would be deleting contains two files 1) document and 2) presentation. We import the os
module and mention the directory path in folder_path extension stores the extension of the file we want to delete here we would delete the document therefore .txt.Next, we begin a for loop for iteration and mention the file_path. After checking if the file is a regular file, we execute the if statement and if not an exception is thrown with an ‘Error deleting {file_path}’ message is displayed, and ‘Deletion done’ is printed after the successful deletion of the file.
About folder:


Output:


Conclusion
Python’s ‘os’ and ‘shutil’ modules make it easy to manage and delete files and directories with a variety of options. Whether you need to delete an entire directory, only specific files, or files with a certain extension, Python has got you covered.
How else can you utilize these modules to manage your files more efficiently?