shutil.rmtree ()
is used to delete an entire directory tree, the path must point to a directory (not a symbolic link to a directory).
Syntax : shutil.rmtree (path, ignore_errors = False, onerror = None)
Parameters:
path: A path -like object representing a file path. A path-like object is either a string or bytes object representing a path.
ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.
Example 1. and the subdirectories are as follows.
# Parent directory:
# Directory inside parent directory:
# File inside subdirectory:
We want to delete the authors directory. Below is the implementation.
|
Exit:
Example 2: by passing ignore_errors = False
.
|
Exit:
Traceback (most recent call last):
File “D: / Pycharm projects / gfg / gfg.py”, line 16, in
shutil.rmtree (path, ignore_errors = False)
File “C: UsersNikhil AggarwalAppDataLocalProgramsPythonPython38-32libshutil.py”, line 730, in rmtree
return _rmtree_unsafe (path, onerror)
File “C: UsersNikhil, AggarwalAppDataLocalPrograms38-Python _rmtree_unsafe
onerror (os.scandir, path, sys.exc_info ())
File “C: UsersNikhil AggarwalAppDataLocalProgramsPythonPython38-32libshutil.py”, line 586, in _rmtree_unsafe
(with path os.scandir ) as scandir_it:
FileNotFoundError: [WinError 3] The system cannot find the path specified: ’D: / Pycharm projects / Python.Engineering / Authors’
Example 3: passing onerror
.
A function must be passed to onerror
, which must contain three parameters.
- function: function that caused the exception.
- path: passed the path that caused the deletion exception
- excinfo: information about the exception called by sys.exc_info ()
Below is a description.
|
Exit:
Inside handler
(, FileNotFoundError (2, ’The system cannot find the path specified’),)
Inside handler
(, FileNotFoundError (2, ’The system cannot find the file specified’), )