To remove a file if it exists in Python, we can use the os.remove()
function from the os
module. However, if the file does not exist, it will raise a FileNotFoundError
exception. Therefore, we need to use error handling to catch that exception.
Here's an example code to remove a file if it exists and handle the exception if it doesn't exist:
main.py352 chars13 lines
In this code, we first check if the file exists using os.path.exists()
function. If the file exists, we try to remove it using os.remove()
function. If the file is successfully removed, we print a success message. If there is any exception while trying to remove the file, we catch the OSError
exception and print an error message. Finally, if the file does not exist, we print a message indicating that the file does not exist.
gistlibby LogSnag