Python Delete File if Exists Example Tutorial

Published On: 25/03/2025 | Category: Python
Python Delete File if Exists Example Tutorial

Hi Guys,

In this Python tutorial, you'll learn how to delete a file if it exists using built-in Python libraries. This is a beginner-friendly guide that demonstrates how to remove a file safely without throwing an error if the file doesn't exist.

This guide will walk you through a step-by-step process on how to check whether a file exists and then delete it using Python's os module. This is especially useful for file automation, clean-up scripts, or batch file removals.

We'll make use of the os module, particularly the functions os.path.exists() and os.remove(). These help ensure that files are deleted only when they actually exist, preventing runtime errors.

You can run this script using Python 3 (recommended).

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!

This Python code snippet first checks if the file exists in the directory, and if it does, it deletes it. Otherwise, it prints a message that the file was not found. This avoids any FileNotFoundError exceptions at runtime.

Happy Pythonic Coding!

Frequently Asked Questions (FAQs)

Q1: How do I check if a file exists in Python?
Use os.path.exists(file_path) to check if a file exists.

Q2: How do I delete a file in Python?
You can delete a file using os.remove(file_path).

Q3: What happens if I try to delete a file that doesn’t exist?
Python will raise a FileNotFoundError unless you check for existence using os.path.exists() first.

Q4: Can I use this method to delete folders?
No. Use os.rmdir() for empty folders or shutil.rmtree() for non-empty folders.

Q5: Is this code compatible with Windows and Linux?
Yes, the os module is cross-platform and works on both Windows and Unix-based systems.

Hope this helps you to keep your file operations safe and efficient!