delete a file in python

To delete a file in Python, we can use the os module which provides a function called remove(). Here's an example code snippet that shows how to use remove() to delete a file:

main.py
import os

# specify the file path
file_path = '/path/to/file.ext'

try:
    # delete the file
    os.remove(file_path)
    print(f"{file_path} has been deleted successfully!")
except FileNotFoundError:
    # handle the case where the file doesn't exist
    print(f"{file_path} does not exist!")
except Exception as e:
    # handle other exceptions like permission denied, etc.
    print(f"Error occurred: {e}")
412 chars
16 lines

In this code, we first import the os module. Then we specify the file path that we want to delete. The try block contains the code that deletes the file using the os.remove() function.

If the file does not exist at the specified path, then the except block with the FileNotFoundError exception will handle it.

If any other error occurs during the execution of os.remove(), like permission denied, etc. then the except block with Exception as the catch-all exception will handle it.

gistlibby LogSnag