Here are two ways to delete a file if it exists in Python.
- Using the “os.remove()” along with “os.path.exists()” functions
- 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,
- A file doesn’t exist at the given path. An error message will be thrown, which we have already seen.
- The user doesn’t have access to the file at the given path.
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.