Delete non-empty Directory recursively in Python

In this article, we have presented the approach to delete non-empty directory recursively in python easily.

Table of contents:

  1. Delete Directory recursively in Python
  2. Complete Code

Delete Directory recursively in Python

Deleting a directory using standard functions or using os module is challenging so it requires directory to be empty.

If the directory has:

  • Files within it
  • Directories within it

then, standard methods fail to delete the directory. The method we will present will delete the directory is all cases.

To delete non-empty directory, we will use shutil library in Python:

import shutil

The rmtree() function of shutil will delete the specified directory irrespective if the directory is non-empty or has nested directories. Everything within the specified directory will be deleted.

shutil.rmtree("directory1", ignore_errors=True)

Note the directory can be deleted only if the directory exists. So, before deleting the directory, we can check if the directory exists and code accordingly.

if os.path.exists("directory1"):
    shutil.rmtree("directory1", ignore_errors=True)

Complete Code

Following is the complete Python code to delete Directory recursively in Python:

import shutil

# Delete non-empty directory named directory1
if os.path.exists("directory1"):
    shutil.rmtree("directory1", ignore_errors=True)
    print ("Directory deleted")
else:
    print ("Directory does not exist")

With this article at OpenGenus, you must have the complete idea of how to delete non-empty directory in Python recursively.