Course outline · 0% complete

0/27 lessons0%

Course overview →

pathlib and context managers

lesson 8-1 · ~12 min · 21/27

Quiz

Warm-up from lesson 8-0: a file object is an iterator over its lines. What happens if you loop over the same open file object a second time?

Paths as objects

In lesson 8-0 you opened files by handing open() a plain string path. Strings work, but they carry no behavior: gluing folders together with + risks the wrong separator on another operating system (Windows uses \, macOS and Linux use /), and questions like "does this file exist?" have no obvious home. The modern tool is pathlib.Path, which turns paths into objects with methods:

from pathlib import Path

p = Path("notes.txt")
p.write_text("line one\nline two\n")
print(p.read_text())
print(p.exists(), p.suffix)   # True .txt

Joining paths uses /, which works on every operating system:

data_file = Path("data") / "users" / "ada.json"

For quick whole-file reads and writes, read_text and write_text are all you need, and they open and close the file for you.

with: the context manager

When you process a file line by line, or append, you still call open. The rule is to always do it inside a with block:

with open("notes.txt") as f:
    for line in f:
        print(line.strip())

with runs a context manager: it guarantees the file is closed when the block ends, even if an exception happens inside. Forgetting to close files leaks resources and can lose buffered writes. The same with pattern manages database connections and locks later in your career, so make it a reflex now: open never appears without with.

Code exercise · python

Run this program. It writes a small file with pathlib, then streams it back line by line with a context manager.

Code exercise · python

Your turn. Write the three scores to scores.txt (one per line), then read the file back and print the TOTAL of the numbers. Use write_text to create the file and a with block to read it.

Quiz

What does with open("a.txt") as f: guarantee?