ItSolutionStuff.com

Python Delete File if Exists Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Post Request with Json File Example

Read Now →

Python Post Request with Basic Authentication Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python Copy File From one Directory to Another Example

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python Get First Date of Last Month Example

Read Now →

Python Get First Date of Next Month Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

How to Compare Two Dates in Python?

Read Now →

How to Check if Today is Saturday or not in Python?

Read Now →

How to Add Minutes to DateTime in Python?

Read Now →