Python Delete File if Exists Example

By Hardik Savani October 30, 2023 Category : Python

Hello,

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:

Example:

main.py

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!

I hope it can help you...

Tags :
Shares