Context Managers
A context manager sets something up, lets a block of code use it, and then cleans it up.
For files, the context manager form is:
The indented block uses the open file. When the block ends, Python closes the file.
Why with matters
Files are operating-system resources. Opening a file asks the system for access. Closing the file releases that access.
This style is easy to forget:
If an error happens before file.close(), the file may stay open longer than
needed.
The with form handles cleanup even if an error occurs inside the block.
The file object is closed after the block
In this pattern:
file is the open file object. text is the contents read from it. A with
block does not create a separate Python name scope, so the name file still
exists afterward—but it refers to a closed file object. Use text, not the
closed file.
Use the contents after the file is closed
Ready to run.
Keep the block small
A good with open(...) block usually does file work only:
Reading is separate from computing. That makes the program easier to test.
In the usual file-reading pattern, what statement closes the file automatically when its block ends?
Answer it first, then check.
HintLook at the block opener
The resource-management statement appears immediately before open(...).
Solutionwith manages cleanup
The with statement enters the file context and closes the file when its
indented block ends, including when an error interrupts the block.