Delete File if Exists in Python Code Example

04-Nov-2022

.

Admin

Delete File if Exists in Python Code Example

Hi Dev,

This post is focused on Delete File if Exists in Python Code Example. This article goes in detailed on How to Check if File Exists in Python and Delete it. We will use How to Remove File if it Exists in Python. you can understand a concept of How to Delete File if 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.

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!

#Python