remove a file if it exists in python

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.py
import os

filename = "example.txt"

if os.path.exists(filename):  # check if the file exists
    try:
        os.remove(filename)  # remove the file
        print(f"{filename} has been deleted successfully!")
    except OSError as error:
        print(f"Error: {filename} could not be deleted. {error}")
else:
    print(f"{filename} does not exist.")
352 chars
13 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