The Wayback Machine - https://web.archive.org/web/20241003005145/https://www.geeksforgeeks.org/delete-an-entire-directory-tree-using-python-shutil-rmtree-method/
Open In App

Delete an entire directory tree using Python | shutil.rmtree() method

Last Updated : 05 Jul, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. 
shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but 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: Suppose the directory and sub-directories are as follow.
# Parent directory:
 

python shutil.rmtree()

# Directory inside parent directory:
 

python shutil.rmtree()

# File inside the sub-directory:
 

python shutil.rmtree()

We want to remove the directory Authors. Below is the implementation.
 

Python3




# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path)


Output:
 

python shutil.rmtree()

Example 2: By passing ignore_errors = False.
 

Python3




# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, ignore_errors = False)
   
# making ignore_errors = True will not raise 
# a FileNotFoundError


Output:
 

Traceback (most recent call last): 
File “D:/Pycharm projects/gfg/gfg.py”, line 16, in 
shutil.rmtree(path, ignore_errors=False) 
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 730, in rmtree 
return _rmtree_unsafe(path, onerror) 
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 589, in _rmtree_unsafe 
onerror(os.scandir, path, sys.exc_info()) 
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 586, in _rmtree_unsafe 
with os.scandir(path) as scandir_it: 
FileNotFoundError: [WinError 3] The system cannot find the path specified: ‘D:/Pycharm projects/GeeksforGeeks/Authors’ 
 

Example 3: By passing onerror. 
In onerror a function should be passed which must contain three parameters. 
 

  • function: function which raised the exception. 
     
  • path: path name passed which raised the exception while removal 
     
  • excinfo: exception info raised by sys.exc_info() 
     

Below is the implementation.
 

Python3




# Python program to demonstrate
# shutil.rmtree()
   
import shutil
import os
   
   
# exception handler
def handler(func, path, exc_info):
    print("Inside handler")
    print(exc_info)
   
   
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
   
# directory
dir = "Authors"
   
# path
path = os.path.join(location, dir)
   
# removing directory
shutil.rmtree(path, onerror = handler)


Output:
 

Inside handler 
(, FileNotFoundError(2, ‘The system cannot find the path specified’), ) 
Inside handler 
(, FileNotFoundError(2, ‘The system cannot find the file specified’), ) 
 

 



Similar Reads

Python | shutil.get_archive_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_archive_formats() method in Python is used to get the list of supported formats for archivin
1 min read
Python | shutil.copy() method
C/C++ Code # Python program to explain shutil.copy() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied su
5 min read
Python | shutil.copy2() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copy2() method in Python is used to copy the content of source file to destination file or direct
4 min read
Python | shutil.get_unpack_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_unpack_formats() method in Python is used to get the list of all supported formats available
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method in Python is to get disk usage statistics about the given path. This method
2 min read
Python | shutil.unregister_unpack_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.unregister_unpack_format() method in Python is used to unregister or remove an unpack format fro
2 min read
Python | shutil.unregister_archive_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.unregister_archive_format() method in Python is used to unregister or remove an archive form
2 min read
Python | shutil.copystat() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copystat() method in Python is used to copy the permission bits, last access time, last modificat
3 min read
Python | shutil.copymode() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories.shutil.copymode() method in Python is used to copy the permission bits from the given source path to
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method tells the disk usage statistics about the given path as a named tuple with t
2 min read
Python | shutil.copytree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the dest
3 min read
Python | shutil.chown() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.chown() method in Python is used to change the owner and /or group of the specified path. Syntax
3 min read
Python | shutil.copyfileobj() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.copyfileobj() method in Python is used to copy the contents of a file-like object to another fil
2 min read
Python | shutil.get_terminal_size() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_terminal_size() method tells the size of the terminal window. As terminal is of the two dime
1 min read
Python | shutil.copyfile() method
Shutil module in Python helps automate the process of copying and removing files and directories. It comes under Python’s standard utility modules. Shutil(short for shell utility) module also provides many functions of high-level operations on files and collections of files. What is Shutil.copyfile() method?The shutil.copyfile() method in Python is
4 min read
Python | shutil.which() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps to automate the process of copying and removal of files and directories. shutil.which() method tells the path to an executable application that would be run if the given cmd
2 min read
Python | shutil.unpack_archive() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. Syntax: shutil.unpack_archiv
2 min read
Python | shutil.move() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removing files and directories. The shutil.move() method moves a file or directory from a source to a destination. It handles directo
2 min read
Shutil Module in Python
Shutil module offers high-level operation on a file like a copy, create, and remote operation on the file. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. In this article, we will learn this module. Copying Files to another directory shutil.copy() method
8 min read
Difference Between os.rename and shutil.move in Python
When it comes to renaming or moving files and directories, two commonly used methods are os. rename and shutil. move. While both can serve the purpose of renaming and moving, they have distinct differences in terms of functionality and use cases. In this article, we will explore these differences and when to use each of them. Difference Between os.
3 min read
Get contents of entire page using Selenium
In this article, we will discuss ways to get the contents of the entire page using Selenium. There can broadly be two methods for the same. Let's discuss them in detail. Method 1: For extracting the visible text from the entire page, we can use the find_element_by_* methods which help us find or locate the elements on the page. Then, We will use th
2 min read
How to Retrieve an Entire Row or Column of an Array in Python?
Arrays are a set of similar elements grouped together to form a single entity, that is, it is basically a collection of integers, floating-point numbers, characters etc. The indexing of the rows and columns start from 0. Uni-Dimensional Arrays Uni-dimensional arrays form a vector of similar data-type belonging elements. It contains a single row of
4 min read
How to print an entire Pandas DataFrame in Python?
When we use a print large number of a dataset then it truncates. In this article, we are going to see how to print the entire Pandas Dataframe or Series without Truncation. There are 4 methods to Print the entire Dataframe. Example # Convert the whole dataframe as a string and displaydisplay(df.to_string())Print Pandas DataFrame in PythonPrint Pand
4 min read
How to Pretty Print an Entire Pandas Series or DataFrame?
In this article, we are going to see how to Pretty Print the entire pandas Series / Dataframe. There are various pretty print options are available for use with this method. Here we will discuss 3 ways to Pretty Print the entire Pandas Dataframe: Use pd.set_options() methodUse pd.option_context() methodUse options.display() MethodCreating DataFrame
3 min read
Remove all columns where the entire column is null in PySpark DataFrame
In this article, we'll learn how to drop the columns in DataFrame if the entire column is null in Python using Pyspark. Creating a spark dataframe with Null Columns: To create a dataframe with pyspark.sql.SparkSession.createDataFrame() methods. Syntax pyspark.sql.SparkSession.createDataFrame() Parameters: dataRDD: An RDD of any kind of SQL data rep
2 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
Check if directory contains files using python
Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(<directory path>) Returns: A list of files pr
3 min read
Finding the largest file in a directory using Python
In this article, we will find the file having the largest size in a given directory using Python. We will check all files in the main directory and each of its subdirectories. Modules required: os: The os module in Python provides a way of using operating system dependent functionality. OS module is available with Python's Standard Library and does
2 min read
Article Tags :
Practice Tags :