Exercises
Paths with pathlib
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Build the path and print its parts, name and suffix.
Python
from pathlib import Path
# build data/reports/march.csv and print parts, name, suffix
Join with the / operator.
from pathlib import Path
p = Path("data") / "reports" / "march.csv"
print(p.parts)
print(p.name)
print(p.suffix)Exercise 2Passed
Write and read a small file in one call each.
Python
from pathlib import Path
# write one line to notes.txt and print it back
write_text and read_text, both with an encoding.
from pathlib import Path
p = Path("notes.txt")
p.write_text("one line\n", encoding="utf-8")
print(p.read_text(encoding="utf-8").strip())Exercise 3Passed
Find every .txt file below the folder, including inside subfolders.
Python
from pathlib import Path
Path("tree/inner").mkdir(parents=True, exist_ok=True)
for name in ["tree/a.txt", "tree/b.csv", "tree/inner/c.txt"]:
Path(name).write_text("x", encoding="utf-8")
# print ['a.txt', 'c.txt']
glob searches one folder; there is a recursive version.
from pathlib import Path
Path("tree/inner").mkdir(parents=True, exist_ok=True)
for name in ["tree/a.txt", "tree/b.csv", "tree/inner/c.txt"]:
Path(name).write_text("x", encoding="utf-8")
print(sorted(p.name for p in Path("tree").rglob("*.txt")))