How to delete a directory tree in Python using shutil.rmtree()

In this article, we will be looking at the shutil.rmtree() method to delete a directory tree using Python. To learn how to delete a file first.

Furthermore, shutil is a standard python module for file operations and manipulations. Shutil consists of high-end file handling methods for file operations. Moreover, file operations include removing or adding directories, creating files or removing the whole directory, etc.

Syntax:- shutil.rmtree(path_of_file, ignore_errors=False, onerror=None)

where:-  path_of_file: is the complete address of the file.
ignore_errors: if true, all the errors while removing the file or directory will be ignored.
onerror: if ignore_errors is false, oneerror uses an error handling mechanism for errors.

Example of shutil.rmtree() to delete directory

1. The below code removes the complete directory by ignoring errors.

Before execution of the code:

delete a directory tree in Python using shutil.rmtree()

 

import shutil
path = "D:/sample/till this folder"
shutil.rmtree(path,ignore_errors=True)

After the execution of the code, the following results are generated:

Example of shutil.rmtree() to delete directory

2. The below code demonstrates an exception handler through onerror, in contrast to, ignore_errors as described above.

onerror takes three arguments, namely, a function that raises the exception, path of the file,  and exception info by sys.exc_info().

 

import shutil
path = "D:/sample/till this folder"
def exc_hand(func , path , exc):
    print("Handler messages : -")
    print(exc)
shutil.rmtree(path , onerror = exc_hand)

As a result, we get the following output:

Example of shutil.rmtree()

In conclusion, I hope you liked the article, write down your queries in the comments below.

Also read: Difference between os.rename and shutil.move in Python

Leave a Reply

Your email address will not be published. Required fields are marked *