Introduction
Deleting directories in Python can be done using the os module and the shutil module. These modules provide functions to delete both empty and non-empty directories.
Using the os Module
The os module provides functions to interact with the operating system. To delete directories, you can use the os.rmdir() function for empty directories and the os.remove() function for files.
os.rmdir()
The os.rmdir() function deletes an empty directory.
Syntax
import os
os.rmdir('directory_name')
Example
import os
# Deleting an empty directory
try:
os.rmdir('example_dir')
print("Directory 'example_dir' deleted successfully.")
except FileNotFoundError:
print("The directory 'example_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except OSError as e:
print(f"Error: {e}")
Output
Directory 'example_dir' deleted successfully.
Using the shutil Module
The shutil module provides high-level operations on files and collections of files. To delete directories, especially non-empty ones, you can use the shutil.rmtree() function.
shutil.rmtree()
The shutil.rmtree() function deletes a directory and all its contents.
Syntax
import shutil
shutil.rmtree('directory_name')
Example
import shutil
# Deleting a non-empty directory
try:
shutil.rmtree('parent_dir')
print("Directory 'parent_dir' and all its contents deleted successfully.")
except FileNotFoundError:
print("The directory 'parent_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
Directory 'parent_dir' and all its contents deleted successfully.
Using the pathlib Module
The pathlib module in Python 3.4+ provides an object-oriented approach to handling filesystem paths. It includes the Path.rmdir() method for deleting empty directories. For non-empty directories, you can combine pathlib with shutil.
Example: Deleting an Empty Directory
from pathlib import Path
# Deleting an empty directory
path = Path('example_dir')
try:
path.rmdir()
print("Directory 'example_dir' deleted successfully.")
except FileNotFoundError:
print("The directory 'example_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except OSError as e:
print(f"Error: {e}")
Output
Directory 'example_dir' deleted successfully.
Example: Deleting a Non-Empty Directory
from pathlib import Path
import shutil
# Deleting a non-empty directory
path = Path('parent_dir')
try:
shutil.rmtree(path)
print("Directory 'parent_dir' and all its contents deleted successfully.")
except FileNotFoundError:
print("The directory 'parent_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
Directory 'parent_dir' and all its contents deleted successfully.
Handling Exceptions
It’s important to handle exceptions that may occur during the deletion process, such as file not found errors, permission errors, and other OS-related errors.
Example
import os
import shutil
# Deleting a directory with exception handling
try:
shutil.rmtree('example_dir')
print("Directory 'example_dir' deleted successfully.")
except FileNotFoundError:
print("The directory 'example_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except OSError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
Output
The directory 'example_dir' does not exist.
Conclusion
Deleting directories in Python is straightforward using the os module for empty directories and the shutil module for non-empty directories. The pathlib module provides a modern, object-oriented approach to filesystem paths and directory deletion. By handling exceptions, you can ensure that your program responds appropriately to errors during the directory deletion process. Understanding these methods is essential for file and directory management tasks in Python applications.