Last updated: Apr 11, 2024
Reading timeยท4 min
Use the shutil.rmtree()
method to recursively delete a directory in
Python.
The method deletes the entire tree of the specified directory.
import shutil import os path_to_directory = './my-directory' # ๐๏ธ True print(os.path.isdir(path_to_directory)) shutil.rmtree(path_to_directory) # ๐๏ธ False print(os.path.isdir(path_to_directory)) print('Directory deleted successfully')
We imported the built-in shutil
module and used the
shutil.rmtree()
method to recursively delete a directory.
The path you pass to the shutil.rmtree()
method must point to a directory
(not a symbolic link of a directory).
I used a relative path in the example, but you can also use an absolute path.
If you are on Windows, you have to prefix the path with an r
to mark it as a
raw string.
# on Windows path_to_directory = r'C:\Users\bobbyhadz\my-directory'
r
enables us to treat backslashes as literal characters and not as escape characters.Alternatively, you can escape each backslash \
with another backslash.
# on Windows path_to_directory = 'C:\\Users\\bobbyhadz\\my-directory'
You can also replace the backslashes with forward slashes when separating the path components.
# on Windows path_to_directory = 'C:/Users/bobbyhadz/my-directory'
An absolute path on macOS or Linux would look something like this:
file_path = '/home/bobbyhadz/Desktop/my-directory
If the specified path to the directory doesn't exist, you would get a FileNotFoundError: [Errno 2] No such file or directory.
For example, if you run the code sample twice:
The shutil.rmtree()
method takes an ignore_errors
argument that you can set
to True
if you want to ignore the errors when running the method.
import shutil import os path_to_directory = './my-directory' # ๐๏ธ False print(os.path.isdir(path_to_directory)) # ๐๏ธ Set ignore_errors to True shutil.rmtree(path_to_directory, ignore_errors=True) # ๐๏ธ False print(os.path.isdir(path_to_directory)) print('Directory deleted successfully')
If ignore_errors
is set to True
, errors resulting from a failed removal
operation are ignored.
You can also use the
os.path.isdir()
method to check if the directory exists before calling shutil.rmtree()
.
import shutil import os path_to_directory = './my-directory' # ๐๏ธ False print(os.path.isdir(path_to_directory)) # ๐๏ธ Set ignore_errors to True if os.path.isdir(path_to_directory): shutil.rmtree(path_to_directory) print('Directory deleted successfully') else: print('The specified directory does NOT exist') # ๐๏ธ False print(os.path.isdir(path_to_directory))
onerror
argumentYou can also set the onerror
argument to a handler function that gets invoked
when an exception occurs while deleting the directory's contents recursively.
import shutil import os path_to_directory = './my-directory' # ๐๏ธ False print(os.path.isdir(path_to_directory)) # ๐๏ธ Set ignore_errors to True def handle_error(function, path, excinfo): print('function', function) print('path: ', path) print('exception info: ', excinfo) shutil.rmtree(path_to_directory, onerror=handle_error)
The onerror
argument can be set to a function that gets called with 3
arguments:
shutil.rmtree()
.sys.exc_info()
.try/except
block to handle potential errorsYou can also use a try/except
block to handle potential errors.
import shutil import os path_to_directory = './my-directory' # ๐๏ธ False print(os.path.isdir(path_to_directory)) try: shutil.rmtree(path_to_directory) print('Recursively deleted directory') except Exception as e: print('Exception: ', e)
We try to recursively delete the directory in the try
block using
shutil.rmtree()
.
If an exception occurs, the except
block runs where we can handle the error.
You can also use the pathlib
module to recursively remove a directory.
from pathlib import Path def recursively_remove_dir(dir_path): directory = Path(dir_path) for item in directory.iterdir(): if item.is_dir(): recursively_remove_dir(item) else: item.unlink() directory.rmdir() print(f'Recurisvely deleted directory {dir_path}') path_to_directory = './my-directory' recursively_remove_dir(path_to_directory)
The pathlib.Path class takes one or more path segments as parameters and creates a PosixPath or a WindowsPath, depending on the operating system.
directory = Path(dir_path)
We used the Path.iterdir method to get path objects of the directory's contents.
for item in directory.iterdir(): if item.is_dir(): recursively_remove_dir(item) else: item.unlink() directory.rmdir() print(f'Recurisvely deleted directory {dir_path}')
You can imagine that the Method returns a generator containing path objects pointing to files or folders located within the specified directory.
p = Path('docs') for child in p.iterdir(): print(child) # Output: # PosixPath('docs/conf.py') # PosixPath('docs/_templates') # PosixPath('docs/make.bat')
On each iteration, we check if the current object is a directory.
If the condition is met, we call the recursively_remove_dir
function with the
directory.
Otherwise, we delete the file using Path.unlink().
Once all of the directory's contents are removed, we use the Path.rmdir method to remove the directory itself.
Note that the directory has to be empty for you to be able to call the rmdir()
method.
os.system()
to recursively delete a directory in PythonYou can also use the os.system() method to recursively delete a directory in a Python script.
The method takes a shell command as a parameter and runs it.
The command you have to issue will be different depending on your operating system.
For example, if you are on macOS or Linux, you can use the rm -rf
command.
# on macOS and Linux import os path_to_directory = './my-directory' os.system(f'rm -rf {path_to_directory}')
If you are on Windows, you would use the rd /s
command instead.
# on Windows import os path_to_directory = r'C:\Users\bobbyhadz\my-directory' os.system(f'rd /s /q {path_to_directory}')
The os.system()
method takes a command and runs it in a subshell.
The os.system()
method is available on Unix and Windows.
You can learn more about the related topics by checking out the following tutorials: