Python Delete File if Exists Example Tutorial
I will show you an example of a python removing the file if it exists. This post will give you a simple example of a python delete file if exists in a directory. we will help you to give an example of a python delete file if exists. I explained step by step how to delete a file if exists in python. You just need some steps to do how to check if a file exists in python and delete it.
To remove a file from a directory in this example, we will utilise the "os" library functions exists() and remove(). So let's try the example below.
File existence is verified via the exists() function.
File will be removed from the path by remove().
You can use these examples with python3 (Python 3) version.
So let's see bellow example:
import os filePath = 'files/image1.png'; # Check File is exists or Not if os.path.exists(filePath): # Delete File code os.remove(filePath) print("The file has been deleted successfully!") else: print("Can not delete the file as it doesn't exists")Output
The file has been deleted successfully!
It will help you....
Happy Pythonic Coding!
How to Use TinyMCE Editor in Django?
How to Trailing URL Slashes in Django?