ItSolutionStuff.com

Python Delete Directory if Exists Example

By Hardik Savani • October 30, 2023
Python

Hello,

In this article we will cover on how to implement python delete directory if exists. I explained simply step by step python delete directory and all contents. In this article, we will implement a python delete folder if exists. I explained simply step by step python remove directory if exists. follow bellow step for python delete folder with all files.

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

exists() will check file is exists or not.

rmtree() will delete directory with all files.

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

let's see below simple example with output:

Example:

main.py

import os
import shutil
  
folderPath = 'files/dataDir';
    
# 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 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 Get First Date of Next Month Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

Python List All Dates Between Two Dates Example

Read Now →

How to Check if Today is Friday or not in Python?

Read Now →