Delete Directory if Exists in Python Code Example

04-Nov-2022

.

Admin

Delete Directory if Exists in Python Code Example

Hi Dev,

Are you looking for example of Delete Directory if Exists in Python Code Example. you will learn Python Delete Folder and All Contents. This post will give you simple example of Python Delete Folder with All Files. I’m going to show you about Python Remove Directory if Exists.

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.

so let's see following examples 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!

#Python