Delete Files
In short: Programmatically removing a file from the file system — unlike manual deletion in a file manager, usually irreversible, with no recycle-bin intermediate step.
In more detail: Before deleting, a program should check whether the file even exists and whether the necessary permissions are present, to avoid unexpected exceptions. Because deletion can’t be undone, many applications instead build in a “soft delete” (only mark the file as deleted, but physically keep it for now).
In Depth
Programmatic deletion differs from manual deletion via a file manager in one decisive point: there’s usually no recycle bin as a safety net. An API call like os.remove(path) removes the file immediately and permanently — a bug in your own code can thereby cause genuine, unintended data loss, with no usual “restore from recycle bin” safety line.
import os
if os.path.exists(path):
try:
os.remove(path)
except PermissionError:
print("No permission to delete.")
else:
print("File does not exist - nothing to delete.")The existence check BEFORE the delete attempt is still only somewhat safe — between the check and the actual delete attempt, another process could theoretically have already removed the file (“race condition”). It’s therefore often more robust to attempt the deletion directly and catch the matching exception, instead of relying on a prior check.
Because of the finality, many applications where data loss would be especially critical rely on soft delete instead of true deletion: the file (or, for database entries, the row) is only marked with a deletion flag (e.g. a deleted_at timestamp) and remains physically present for now. Only after a certain period expires — or never — is it actually permanently removed. This allows accidental deletions to be undone, but permanently costs storage space and makes queries somewhat more complex (every query has to filter for “not deleted” too).
A related but technically different concept is deleting entire directories — here, it additionally has to be decided whether only empty directories may be deleted or whether the entire content is recursively deleted along with it (the latter is especially dangerous with faulty path specifications).
See also: Files, Exceptions