Python Delete Directory if Exists Example Tutorial

Published On: 21/10/2022 | Category: Python


Hi Guys,

I will explain step by step tutorial python delete directory if exists. let’s discuss about python delete folder if exists. This tutorial will give you simple example of python remove directory if exists. In this article, we will implement a python delete folder with all files.

To delete a folder containing all files in this example, we will utilise the functions exists() and rmtree() of the "os" and shutil library. So let's try the example below.

File existence is verified via the exists() function.

rmtree() will delete directory with all files.

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

So let's see bellow example:

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!

It will help you....

Happy Pythonic Coding!