liveBook · Manning

With statement

As explained in The Quick Python Book, Fourth Edition

A with statement is a Python control-flow construct that establishes a context manager-controlled block and performs its exit actions when the block ends.

A with statement runs a block under a context manager. The manager handles entry and departure, so routine cleanup occurs even when an exception interrupts the block. section 3.4.8 section 14.3

Use the construct when a resource has a predictable beginning and end:

  • Bind the managed object with `as`, as in `with open("myfile", "r") as file:`. section 13.1
  • Keep resource operations inside the indented block; the file closes when the block ends, without an explicit `close()` call. section 13.2 section 14.3
  • Replace a longer `try`/`finally` cleanup pattern when the object supplies context-management behavior. section 3.4.8 section 14.3
  • Manage multiple resources in one statement, or split a parenthesized statement across lines in Python after 3.10. section 14.3

Read and close a file safely

with open("myfile", "r") as file: for line in file: print(line) The file is closed after the loop, including when an exception occurs inside the block. The same pattern can open an input and output file together. section 3.4.8 section 14.3

with open(filename) as infile:
   data = infile.read()

Browse the compact file-reading form that replaces explicit try/finally cleanup. section 14.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains syntax, exception-safe cleanup, multiple managers, and multiline form, but defers custom-manager construction to contextlib documentation.
Examples
Demonstrates reading files, copying between files, explicit try-finally cleanup, and parenthesized multiline managers.
What it assumes
Assumes general Python and file-I/O knowledge while introducing context managers as a safer alternative to manual closure.
What you can do after
Apply it via Python’s context-manager protocol to read or write files while ensuring cleanup after success or failure.
How it connects
Connects context managers with file objects, exceptions, try-finally, resource management, and database transactions.

Also explained in

Compare how 6 books explain with statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.