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.
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!")
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,
- 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.
- 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.
The unlink() function takes a filePath as an argument which is the file to the path.
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.