Delete Folder and Files Recursively in Python Example

30-Sep-2022

.

Admin

Delete Folder and Files Recursively in Python Example

Hi Dev,

In this post, we will learn Delete Folder and Files Recursively in Python Example. I’m going to show you about Python Delete Files in Subdirectories. We will use Python Delete Folder and Files Recursively. This article will give you simple example of Python Recursive Delete.

In this example, we will use exists() and rmtree() of "os" and shutil library to delete all folder and files recursively. so let's see below example and do it.

exists() will check file is exists or not.

rmtree() will delete directory with all files recursively.

so let's see following examples with output:

Example:


I have created following files on files folder and remove all files and folders:

files/test.txt

files/demo/test.txt

files/test/test.txt

main.py

import os

import shutil

folderPath = 'files/';

# Check Folder is exists or Not

if os.path.exists(folderPath):

# Delete Folder code

shutil.rmtree(folderPath)

print("The folder has been deleted successfully!")

else:

print("Can not delete the folder as it doesn't exists")

Output:

The folder has been deleted successfully!

#Python