Deleting files
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Deleting and checking files is the job of the os module:
import os
os.path.exists("notes.txt") # does the file (or folder) exist
os.path.isfile("notes.txt") # is it a file specifically?
os.remove("notes.txt") # delete the file
os.listdir(".") # list of files in the folder
os.mkdir("backup") # create a folder
os.rmdir("backup") # delete an EMPTY folder
Deletion is irreversible: there's no recycle bin; the file disappears at once.
If the file doesn't exist, os.remove raises a FileNotFoundError. There are two approaches:
# 1. Check first
if os.path.exists(path):
os.remove(path)
# 2. Try it and catch the error
try:
os.remove(path)
except FileNotFoundError:
pass
The second is more reliable: the file could disappear between the check and the deletion. In Python this style is called EAFP: "it's easier to ask for forgiveness than permission".
A modern alternative to the os module is pathlib: Path("notes.txt").unlink(missing_ok=True).
Task. Write a function safe_delete(path): it deletes the file and returns True, and if the file wasn't there, it returns False and doesn't crash.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.