Delete a Directory and Its Contents in Python

In Python, you can delete a directory and all its contents using the shutil.rmtree() function from the shutil module. This method allows for the complete removal of a folder, including all files and subdirectories within it. Additionally, other methods like os.rmdir() or pathlib.Path.rmdir() can be used for removing empty directories. In this tutorial, we will explore different ways to delete a directory and its contents in Python.


Examples to Delete a Directory and Its Contents

1. Deleting a Non-Empty Directory using shutil.rmtree()

We will use the shutil.rmtree() function to delete a non-empty directory sample_directory. This method removes the directory and all its files and subdirectories. Replace sample_directory with the name of directory you would like to delete.

main.py

</>
Copy
import shutil

# Specify the directory to be deleted
dir_path = "sample_directory"

# Delete the directory and its contents
shutil.rmtree(dir_path)

print(f"Directory '{dir_path}' has been deleted.")

Explanation:

  1. We import the shutil module, which provides file operations.
  2. The variable dir_path is set to the directory name we want to delete.
  3. The shutil.rmtree(dir_path) function is called, which removes the specified directory and all its contents.
  4. Finally, we print a confirmation message indicating the directory has been deleted.

Output:

Directory 'sample_directory' has been deleted.

2. Deleting an Empty Directory using os.rmdir()

The os.rmdir() function can only delete empty directories. If the directory contains files or subdirectories, an error will be raised.

main.py

</>
Copy
import os

# Specify the empty directory to be deleted
empty_dir = "sample_directory"

# Delete the empty directory
os.rmdir(empty_dir)

print(f"Empty directory '{empty_dir}' has been deleted.")

Explanation:

  1. We import the os module, which allows interaction with the operating system.
  2. The variable empty_dir is set to the name of the empty directory to be deleted.
  3. We call os.rmdir(empty_dir), which removes the directory if it is empty.
  4. A success message is printed after the directory is deleted.

Output:

Empty directory 'sample_directory' has been deleted.

3. Handling Errors When Deleting a Directory

When attempting to delete a directory, errors may occur if the directory does not exist or is in use. We can handle such errors using a try-except block.

main.py

</>
Copy
import shutil
import os

# Specify the directory to delete
dir_to_delete = "sample_directory"

try:
    shutil.rmtree(dir_to_delete)
    print(f"Directory '{dir_to_delete}' has been deleted.")
except FileNotFoundError:
    print(f"Error: Directory '{dir_to_delete}' not found.")
except PermissionError:
    print(f"Error: Permission denied while deleting '{dir_to_delete}'.")

Explanation:

  1. We import the shutil and os modules.
  2. The variable dir_to_delete holds the directory name we want to delete.
  3. A try block is used to attempt directory deletion with shutil.rmtree(dir_to_delete).
  4. If the directory does not exist, a FileNotFoundError is caught, and an error message is displayed.
  5. If permission issues occur, a PermissionError is caught, and a relevant error message is printed.

Output (If directory exists):

Directory 'sample_directory' has been deleted.

Output (If directory does not exist):

Error: Directory 'sample_directory' not found.

4. Deleting a Directory Using pathlib.Path.rmdir()

The pathlib module provides an object-oriented approach to file handling. The Path.rmdir() method can delete an empty directory.

main.py

</>
Copy
from pathlib import Path

# Specify the empty directory
dir_path = Path("sample_directory")

# Delete the directory if it's empty
dir_path.rmdir()

print(f"Empty directory '{dir_path}' has been deleted.")

Explanation:

  1. We import Path from the pathlib module.
  2. A Path object is created with the directory name dir_path.
  3. The rmdir() method is called to delete the directory if it is empty.
  4. A success message confirms the deletion.

Output:

Empty directory 'sample_directory' has been deleted.

Conclusion

Python provides multiple methods for deleting directories:

  1. shutil.rmtree(): Deletes a directory and all its contents.
  2. os.rmdir(): Deletes an empty directory only.
  3. pathlib.Path.rmdir(): Object-oriented way to delete an empty directory.
  4. Handling errors using try-except ensures robustness.