This Python Delete Files lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
pathlib.Path.unlink deletes one file. missing_ok=True avoids an error when the file is already gone.
Deleting a folder is rmdir, and it refuses a folder that still has files. There is no undo.
Example 1: Start here
Check the path twice before you delete. A relative path depends on the folder you started Python from.
from pathlib import Path # load a tool that comes with Python
target = Path("draft.tmp") # a file path
print(target.name)
print("unlink removes that file on disk")
Example 2: Decide before you remove
Removing a name from a list is the safe rehearsal. On disk, Path(target).unlink deletes the file.
files = ["draft.tmp", "notes.txt"] # a list; the values stay in this order
target = "draft.tmp" # text
files = [name for name in files if name != target] # a list; the values stay in this order
print(files)
Example 3: Missing is acceptable
missing_ok=True means unlink does not raise an error when the file is already gone.
files = ["notes.txt"] # a list; the values stay in this order
target = "draft.tmp" # text
print(target in files) # in is True when the value is found
Example 4: A folder must be empty
rmdir refuses a folder that still contains files. Empty it first.
folder = [] # a list; the values stay in this order
if not folder: # run the indented lines only when this is true
print("safe to remove the folder")
