
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Entire Non-Empty Directory Trees Using Python
In Python, when we are working with files and directories, it's common to delete a folder that contains other files and subfolders. To delete such non-empty directories, Python provides different methods to remove entire directory trees safely and efficiently.
Removing Directories Using shutil.rmtree()
In Python, we have the shutil.rmtree() method is used to delete an entire directory along with all its files and subdirectories. This method is straightforward and ideal for cleaning up directories recursively. This method takes the name of the directory or files as input.
Following is the syntax of the shutil.rmtree() method -
import shutil shutil.rmtree("folder_path")
Note: Once we delete the file or directory, it will be permanently deleted.
Example
Following example creates a directory structure with nested folders and files and then deletes the entire directory using shutil.rmtree() method -
import os import shutil # Create nested folders and files os.makedirs("demo_folder/subfolder", exist_ok=True) with open("demo_folder/file1.txt", "w") as f: f.write("Sample file 1") with open("demo_folder/subfolder/file2.txt", "w") as f: f.write("Sample file 2") # Delete the directory and its contents shutil.rmtree("demo_folder")
When we run the above program, the folder with the name demo_folder will be created, and everything inside that folder will be deleted permanently.
Exception Handling
As we know, Exception Handling is used to manage unexpected events easily. If we try to delete a directory that doesn't exist or we don't have permission to delete, then Python will raise an error. We can handle such cases using Exception Handling.
Example
Following is the example, in which we are using the method shutil.mtree() with Exception Handling to remove the non-empty directory trees in Python -
import shutil try: shutil.rmtree('D:\Tutorialspoint\sample\demo_folder') print("Directory successfully removed.") except FileNotFoundError: print("The directory was not found.") except PermissionError: print("Permission denied while trying to delete the directory.") except Exception as e: print(f"An error occurred: {e}")
Custom Deletion Using os.walk()
If we want more control during the deletion process, e.g., skipping certain files or logging each step, then we can use the os.walk() method to traverse the directory tree manually and delete files and folders from the bottom up. Here is an example of using os.walk() to remove non-empty directory trees in Python -
import os target_dir = 'D:\Tutorialspoint\sample\demo_folder' for root, dirs, files in os.walk(target_dir, topdown=False): for file in files: os.remove(os.path.join(root, file)) for directory in dirs: os.rmdir(os.path.join(root, directory)) os.rmdir(target_dir)
This method is flexible by allowing us to perform actions before or after deleting each file or subdirectory.
Validating Directory Before Deletion
It is necessary to check whether the directory exists before deleting it. We can use os.path.exists() method to confirm the presence of the directory or file -
import os import shutil dir_to_delete = 'target_folder' if os.path.exists(dir_to_delete): shutil.rmtree(dir_to_delete) print("Directory deleted.") else: print("No such directory found.")