Python Delete/Remove a File If Exists On Disk

In Python, you can remove/delete a file from disk using the os module’s remove function.

Here’s an example:

import os

file_path = "path/to/file.txt"

if os.path.exists(file_path):
os.remove(file_path)
print("File removed successfully.")
else:
print("File not found.")

In this example, we first check if the file exists using the os.path.exists function. If the file exists, we remove it using the os.remove function. If the file does not exist, we print a message indicating that the file was not found.

Leave a Comment