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!
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?