UcenlyOpen in the app

Programming Essentials · BE5B33PRG · Topic 6 of 9

Files and paths

Open resources safely and distinguish data from path location.

Open the interactive lesson

Key ideas

Read

with open(path, encoding="utf-8") as f: manages closing; for line in f: streams lines.

Write

with open(path, "w", encoding="utf-8") as f: f.write(text) replaces content; "a" appends.

Paths

A relative path is resolved from the current working directory; an absolute path starts at the filesystem root.

In one line: Use with for file lifetime and check which directory a relative path means.

Sources

Written by Ucenly. Based on the BE5B33PRG course materials: