delete a directory in python

To delete a directory in Python, you can use the os module's rmdir() or removedirs() methods. Here's an example code snippet to remove a directory:

main.py
import os

dirPath = "/path/to/directory"

try:
    os.rmdir(dirPath)
    print(f"Directory '{dirPath}' has been removed successfully!")
except OSError as e:
    print(f"Error: {dirPath} : {e.strerror}")
204 chars
10 lines

Here, dirPath is the path of the directory you want to remove. The code first tries to remove the directory using the os.rmdir() method. If the directory is not empty, it raises an OSError, so you can catch the exception and handle it appropriately.

Alternatively, you can use the shutil module's rmtree() method to recursively delete a directory and all its contents. Here's an example code snippet to remove a directory recursively:

main.py
import shutil

dirPath = "/path/to/directory"

try:
    shutil.rmtree(dirPath)
    print(f"Directory '{dirPath}' and its contents have been removed successfully!")
except OSError as e:
    print(f"Error: {dirPath} : {e.strerror}")
231 chars
10 lines

Here, shutil.rmtree() method is used to remove the directory and all its contents. Similarly, if an exception is raised, you can catch and handle it appropriately.

gistlibby LogSnag