How to Delete File If Exists in Python

Here are two ways to delete a file if it exists in Python.

  1. Using the “os.remove()” along with “os.path.exists()” functions
  2. Using the “os.ulink()” method

Method 1: Using the os.remove() along with os.path.exists() function

To delete a file if it exists in Python, you can use the os.remove() function along with the os.path.exists() to check if the file exists before attempting to remove it.

import os

if os.path.exists("app.cpp"):
  os.remove("app.cpp")
  print("The file has been deleted successfully")
else:
  print("The file does not exist!")

Output

The file has been deleted successfully

The file is there; that’s why it was successfully deleted.

If you try to execute the above script again, you will get the following output.

The file does not exist!

Before removing the file, it checks if it exists; in our case, it does not. So, it returns the “File does not exist!” output.

Error handling in os.remove()

The os.remove() function can throw an OSError if,

  1. A file doesn’t exist at the given path. An error message will be thrown, which we have already seen.
  2. The user doesn’t have access to the file at the given path.
  3. Passing the directory to the os.remove() function will throw the error.

Method 2: Using the os.ulink() function

Python os.ulink() function can be used to remove a file.

Syntax

os.unlink(filePath)

Parameters

filePath: The unlink() function takes a filePath as an argument which is the file to the path.

Example

I have created an app.cpp file in the current directory.

import os

# Handle errors while calling os.ulink()
try:
  os.ulink("app.cpp")
except:
  print("Error while deleting file") 

If the file exists, then it will remove the file. If it does not, it will execute the except block, which prints “Error while deleting file”.

That is pretty much it for removing a file if it exists in Python.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.