Python Delete File if Exists Example
In this tutorial, I will show you python delete file if exists in directory. We will look at example of python remove file if exists. In this article, we will implement a python delete file if exists. I would like to show you how to delete file if exists in python. Let's see bellow example how to remove file if it exists in python.
In this example, we will use exists() and remove() of "os" library to delete file from directory. so let's see below example and do it.
exists() will check file is exists or not.
remove() will delete file from path.
You can use these examples with python3 (Python 3) version.
let's see below simple example with output:
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")
The file has been deleted successfully!
I hope it can help you...
We are Recommending you
- Python Post Request with Json File Example
- Python Post Request with Basic Authentication Example
- Python Post Request with Bearer Token Example
- Python Copy File From one Directory to Another Example
- Python Get File Extension from Filename Example
- Python Get First Date of Last Month Example
- Python Get First Date of Next Month Example
- Python Create Zip Archive from Directory Example
- How to Compare Two Dates in Python?
- How to Check if Today is Saturday or not in Python?
- How to Add Minutes to DateTime in Python?