ItSolutionStuff.com

Python Delete Folder and Files Recursively Example

By Hardik Savani • October 30, 2023
Python

This is a short guide on python delete files recursively. This article will give you simple example of python remove files recursively. step by step explain python delete all files recursively. if you have questions about python remove all files recursively then I will give a simple example with a solution. You just need to do some steps to do 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.

You can use these examples with python3 (Python 3) version.

let's see below simple example 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!

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Delete Directory if Exists Example

Read Now →

Python Delete File if Exists Example

Read Now →

Python Post Request with pem File Example

Read Now →

Python Post Request with Json File Example

Read Now →

Python Post Request with Basic Authentication Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python Copy File From one Directory to Another Example

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python Get First Date of Last Month Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

How to Compare Two Dates in Python?

Read Now →

Python Subtract Seconds from DateTime Example

Read Now →