Chapters
Python114 chapters

Exercises

Delete Files

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Create a file, delete it, and print whether it still exists.

Python
import os

with open("scratch.txt", "w", encoding="utf-8") as f:
    f.write("temporary")

# delete it, then print os.path.exists
Exercise 2

Delete a file that may not exist, without a race and without crashing.

Python
# delete gone.txt safely, then print done
Exercise 3

Delete only the .tmp files and leave keep.txt alone.

Python
from pathlib import Path

for name in ["a.tmp", "b.tmp", "keep.txt"]:
    Path(name).write_text("x", encoding="utf-8")

# remove the .tmp files
print(sorted(p.name for p in Path(".").glob("*.t*")))