How to recursively delete a Directory in Python

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# How to recursively delete a Directory in Python

Use the shutil.rmtree() method to recursively delete a directory in Python.

The method deletes the entire tree of the specified directory.

main.py
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')

recursively delete directory in python

The code for this article is available on GitHub

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.

main.py
# on Windows path_to_directory = r'C:\Users\bobbyhadz\my-directory'
Prefixing the string with an r enables us to treat backslashes as literal characters and not as escape characters.

Alternatively, you can escape each backslash \ with another backslash.

main.py
# on Windows path_to_directory = 'C:\\Users\\bobbyhadz\\my-directory'

You can also replace the backslashes with forward slashes when separating the path components.

main.py
# on Windows path_to_directory = 'C:/Users/bobbyhadz/my-directory'

An absolute path on macOS or Linux would look something like this:

main.py
file_path = '/home/bobbyhadz/Desktop/my-directory

# Handle the error if the directory doesn't exist

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:

  1. You would recursively delete the directory the first time.
  2. You would get an error the second time the script is run because the directory no longer exists.

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.

main.py
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')

ignore errors when deleting directory recursively

The code for this article is available on GitHub

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().

main.py
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))

check if directory exists before deleting it recursively

The code for this article is available on GitHub

# Handling the potential error with the onerror argument

You can also set the onerror argument to a handler function that gets invoked when an exception occurs while deleting the directory's contents recursively.

main.py
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)

handle errors while deleting directory recursively

The code for this article is available on GitHub

The onerror argument can be set to a function that gets called with 3 arguments:

  1. The function that raised the exception (depends on the platform and implementation).
  2. The path that was passed to shutil.rmtree().
  3. The exception information returned by sys.exc_info().

# Using a try/except block to handle potential errors

You can also use a try/except block to handle potential errors.

main.py
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)
The code for this article is available on GitHub

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.

# Recursively remove a directory in Python using pathlib

You can also use the pathlib module to recursively remove a directory.

main.py
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)

recursively remove directory using pathlib

The code for this article is available on GitHub

The pathlib.Path class takes one or more path segments as parameters and creates a PosixPath or a WindowsPath, depending on the operating system.

main.py
directory = Path(dir_path)

We used the Path.iterdir method to get path objects of the directory's contents.

main.py
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.

main.py
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.

# Using os.system() to recursively delete a directory in Python

You 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.

main.py
# 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.

main.py
# 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev