How to Delete a File if it Exists in Python?

In this tutorial, I will explain how to delete a file if it exists in Python. As a Python developer working on a project for one of my clients, I came across a scenario where I needed to delete a file which is existing, this made me explore more about this topic. I will share my findings with examples and screenshots.

Delete a File if it Exists in Python

Deleting a file involved generating temporary files that needed to be deleted after processing. To ensure the program ran without interruptions, we had to check if these files existed before attempting to delete them.

Read How to Create a File in Python if It Doesn’t Exist?

Step 1. Import Necessary Modules

Python provides several modules for file operations. For this task, we’ll use the os module, which includes functions for interacting with the operating system.

import os

Step 2. Check if the File Exists

Before deleting a Python file, it’s crucial to check if it exists. The os.path.exists() function is perfect for this job. It returns True if the file exists and False otherwise.

file_path = "C:/Users/JohnDoe/Documents/tempfile.txt"

if os.path.exists(file_path):
    # Proceed to delete the file

Check out How to Write JSON Data to a File in Python?

Step 3. Delete the File

Once you’ve confirmed the file exists, you can safely delete it using the os.remove() function.

if os.path.exists(file_path):
    os.remove(file_path)
    print(f"The file {file_path} has been deleted successfully.")
else:
    print(f"The file {file_path} does not exist.")

Full Example

Here’s the complete code wrapped together:

import os

file_path = "C:/Users/JohnDoe/Documents/tempfile.txt"

if os.path.exists(file_path):
    os.remove(file_path)
    print(f"The file {file_path} has been deleted successfully.")
else:
    print(f"The file {file_path} does not exist.")

I executed the above example code and added the screenshot below.

Delete a File if it Exists in Python

Read How to Overwrite a File in Python?

Handle Exceptions

While the above method works well, it’s also good practice to handle potential exceptions. For instance, if the Python file is in use by another process, attempting to delete it will raise an OSError. You can handle this using a try-except block.

try:
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"The file {file_path} has been deleted successfully.")
    else:
        print(f"The file {file_path} does not exist.")
except OSError as e:
    print(f"Error: {e.strerror}")

I executed the above example code and added the screenshot below.

How to Delete a File if it Exists in Python

Check out How to Rename Files in Python?

Additional Tips

1. Delete Multiple Files

If you need to delete multiple files, you can use a loop to iterate through a list of file paths.

file_paths = [
    "C:/Users/JohnDoe/Documents/tempfile1.txt",
    "C:/Users/JohnDoe/Documents/tempfile2.txt",
    "C:/Users/JohnDoe/Documents/tempfile3.txt"
]

for file_path in file_paths:
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            print(f"The file {file_path} has been deleted successfully.")
        else:
            print(f"The file {file_path} does not exist.")
    except OSError as e:
        print(f"Error: {e.strerror}")

I executed the above example code and added the screenshot below.

Delete a File if it Exists in Python Multiple Files

Read How to Check if a File is Empty in Python?

2. Use pathlib for Path Operations

Python’s pathlib module offers an object-oriented approach to file system paths and can be used as an alternative to os.path.

from pathlib import Path

file_path = Path("C:/Users/JohnDoe/Documents/tempfile.txt")

if file_path.exists():
    file_path.unlink()
    print(f"The file {file_path} has been deleted successfully.")
else:
    print(f"The file {file_path} does not exist.")

Conclusion

In this tutorial, I explained how to delete a file if it exists in Python. I discussed the step-by-step process of deleting a file if it exists in Python and gives the full code that can be run and saw how to handle exceptions. And also learned some additional tips for deleting multiple files, and using pathlib for path operations.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.