with / Context Manager (Python)

The with statement sets up and automatically cleans up a resource, such as a file, even if an error happens. The object it manages is called a context manager.

Python

The most common use is opening files: `with open(...) as f` guarantees the file is closed when the block ends, so you never forget to close it.

Syntax

with resource as name:
    ...

Examples

Python

with open("note.txt", "w") as f:
    f.write("hello")
# file is closed automatically here

Learn it in a lesson

See also

Back to the Dictionary