clean directory contents

Python -- Posted on Dec. 19, 2019

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:

  1. Import the necessary modules: os and shutil.

  2. Define the function delete_directory_contents(directory_name) that takes the directory_name as input, which is the path of the directory whose contents need to be deleted.

  3. Inside the function, use a for loop to iterate through each item (file or subdirectory) present in the specified directory (directory_name). The os.listdir() function returns a list of all the items in the directory.

  4. For each item, construct its full path using os.path.join() by combining the directory_name with the item's name.

  5. Use a try block to handle any exceptions that may arise during the deletion process.

  6. If the item is a regular file (os.path.isfile(file_path)) or a symbolic link (os.path.islink(file_path)), use os.unlink() to delete it.

  7. If the item is a directory (os.path.isdir(file_path)), use shutil.rmtree() to recursively remove the entire directory along with its contents.

  8. 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))
                  
   
            

Related Posts