To remove a non-empty directory in Python, the easiest way is to use the shutil module rmtree() function.

import shutil

shutil.rmtree(path)

When working with files and folders in Python, the ability to easily create or delete files and folders can be useful.

One such situation is if you want to remove a non-empty directory.

The shutil module rmtree() function allows you to delete an entire directory tree given a path.

With rmtree(), you can delete any directory and all of its contents. rmtree() takes three parameters.

shutil.rmtree(path, ignore_errors=False, onerror=None)

The first parameter is a string representing the path of the directory you want to remove. The second parameter, ‘ignore_errors’ allows you to ignore any errors that may occur when attempting to delete a directory and its contents. For the third parameter, ‘onerror’, you can pass a function which will handle any errors that may occur during the attempted removal of the directory.

Below is a simple example showing you how to delete a directory with rmtree() in Python.

import shutil

shutil.rmtree(path)

Hopefully this article has been useful for you to learn how to remove non-empty directories using Python.

Categorized in:

Python,

Last Update: March 22, 2024