AppDividend
Latest Code Tutorials

How to Delete File If Exists in Python

To deal with file-related operations in Python, use the OS module. In this article, we will see how to remove a file if it exists using the os.remove() and os.ulink() function.

Python delete file if exists

To delete a file if exists in Python, use the os.path.exists() and os.remove() method. To avoid getting an error while deleting a file, use the os.path.exists() before executing the os.remove() method.

To use the OS module, we need to import it at the head of the file.

import os

In my current directory, there is one file called app.cpp. We will remove that file, but before that, we will check if it exists, and if it does, we will remove it.

Now let’s write a code to remove a file if it exists.

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.

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

The file does not exist!

Before removing the file, it checks if it exists, and 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. If you pass the directory to the os.remove() function, it will throw the error.

Remove a file using os.ulink()

The os.ulink() is a built-in Python function that removes a file.

Syntax

os.unlink(filePath)

Arguments

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

Example

I have created an app.cpp file to 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 Reply

Your email address will not be published.

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