The function delete_directory_contents
you provided is designed to delete all the contents (files and subdirectories) within a specified directory. It uses the os
and shutil
modules in Python to perform the deletion.
Here's a step-by-step explanation of the function:
-
Import the necessary modules:
os
andshutil
. -
Define the function
delete_directory_contents(directory_name)
that takes thedirectory_name
as input, which is the path of the directory whose contents need to be deleted. -
Inside the function, use a
for
loop to iterate through each item (file or subdirectory) present in the specified directory (directory_name
). Theos.listdir()
function returns a list of all the items in the directory. -
For each item, construct its full path using
os.path.join()
by combining thedirectory_name
with the item's name. -
Use a
try
block to handle any exceptions that may arise during the deletion process. -
If the item is a regular file (
os.path.isfile(file_path)
) or a symbolic link (os.path.islink(file_path)
), useos.unlink()
to delete it. -
If the item is a directory (
os.path.isdir(file_path)
), useshutil.rmtree()
to recursively remove the entire directory along with its contents. -
If any exception occurs during the deletion, the function will catch it and print an error message indicating which file or directory could not be deleted and the reason for the failure.
It's worth noting that this function does not delete the specified directory itself, only its contents. If you want to delete the entire directory (including the directory itself), you should do it separately using os.rmdir()
or shutil.rmtree()
on the directory itself after using this function to clear its contents.
Remember to use this function with caution, as it will permanently delete files and directories within the specified directory, and the operation cannot be undone. Always double-check and make sure you have a backup if necessary before using this function.
import os,shutil
def delete_direcory_contents(directory_name):
'''
Delete directory contents
'''
for filename in os.listdir(directory_name):
file_path = os.path.join(directory_name, 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))