Exercises
Delete Files
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
os.remove takes the path.
import os
with open("scratch.txt", "w", encoding="utf-8") as f:
f.write("temporary")
os.remove("scratch.txt")
print(os.path.exists("scratch.txt"))Exercise 2Passed
Delete a file that may not exist, without a race and without crashing.
Python
# delete gone.txt safely, then print done
Path.unlink takes missing_ok.
from pathlib import Path
Path("gone.txt").unlink(missing_ok=True)
print("done")Exercise 3Passed
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*")))glob("*.tmp") matches by pattern.
from pathlib import Path
for name in ["a.tmp", "b.tmp", "keep.txt"]:
Path(name).write_text("x", encoding="utf-8")
for path in Path(".").glob("*.tmp"):
path.unlink()
print(sorted(p.name for p in Path(".").glob("*.t*")))