Python lets you delete files from your system using the os module. You can remove individual files, check if a file exists before deleting it, or loop through a list of filenames. File deletion is permanent, so always be careful to avoid accidental data loss.
os.remove(path) deletes a file at the given path.os.unlink(path) is effectively the same as os.remove().os.path.exists(path) to check if a file exists before deleting.To work with file deletion, you first import the os module:
os.remove(path) and os.unlink(path) both remove the file specified by path. If the file does not exist, a FileNotFoundError is raised. That’s why it is a good practice to check with os.path.exists(path) before deleting.
When deleting multiple files, you typically store their names in a list and then iterate over that list, deleting each file that exists and optionally printing a message for those that do not.
import os
os.remove("example.txt") # Deletes the file named 'example.txt'
import os
if os.path.exists("example.txt"): # Check if the file exists before deleting
os.remove("example.txt") # Delete the file only when it exists
else:
print("The file does not exist") # Handle the case where the file is missing
import os
os.unlink("example.txt") # Deletes the file using os.unlink()
import os
files = ["file1.txt", "file2.txt", "file3.txt"] # List of files to delete
for f in files: # Loop through each file name
if os.path.exists(f): # Delete only if the file exists
os.remove(f)
else:
print(f"{f} does not exist") # Inform when a file is missing
In the multiple-file deletion example, Python will:
file2.txt does not exist when it can’t find a file.This pattern prevents your script from crashing due to FileNotFoundError and also makes it clear which files were successfully deleted and which were missing.
file_path instead of just f in real projects.os.remove() and os.unlink() work only for files, not directories.example.txt and delete it using os.remove().os.unlink() instead of os.remove() and confirm it behaves the same.y/n) before deleting each file.