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.py204 chars10 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.py231 chars10 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