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





