The with-blocks
Up to now our examples have all followed a pattern: open() a file, work with the file, close() the file. The close() is important because it informs the underlying operating system that you're done working with the file. If you don't close a file when you're done with it, it's possible to lose data. There may be pending writes buffered up which might not get written completely. Furthermore, if you're opening lots of files, your system may run out of resources. Since we always want to pair every open() with a close(), we would like a mechanism that enforces the relationship even if we forget.
This need for resource clean up is common enough that Python implements a specific control flow structure called with-blocks to support ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access