Context managers and with

Files, network connections and locks must be closed or released when you're done. Calling f.close() yourself is fragile: if anything raises first, the close never runs.

with open(path) as f: closes the file when the block ends, however it ends: normally, by return, or by an exception. That guarantee is the whole point. An object that works with with is called a context manager.

Writing and reading files works here in the browser. They go to a small in-memory folder that disappears when you reload. Pass encoding="utf-8" in real code so the result doesn't depend on the machine.

Iterating over a file gives one line at a time, newline included, without loading the whole file into memory.

Other context managers you'll meet: threading.Lock, tempfile.TemporaryDirectory and contextlib.suppress.

Run it, then read the file with f.read() instead of the loop.