There are a few Python library classes which provide context
information that is used by the
most commonly-used class is the
There are two forms of the
the first, the context object does not provide a context-specific object
to work with. In the second, the context provides us an object to be
used within the context.
We'll look at the second form, since that is how the
file class works. A
object is a kind of context manager, and responds to the protocol
defined by the
When we open a file for processing, we are creating a context.
When we leave that context, we want to be sure that the file is properly
closed. Here's the standard example of how this is used.
with file('someData.txt','r') as theFile:
for aLine in theFile:
# the file was closed by the context manager
We create the file, which can be used as a context manager.
statement enters the context, which
returns a file object that we can use for input and output
clause specifies that the
working object is assigned to
This is a pretty typical
that reads each line of a file.
statement also exits the
context, irrespective of the presence or absence of exceptions. In
the case of a
file context manager, this
will close the file.
In the previous example, we saw that the file factory function is
used to create a context manager. This is possible because a file has
several interfaces: it is a context manager as well as being a working
file object. This is potentially confusing because it conflate file
context manager with the working file object. However, it also
Thas the advantage of making the
optional. In many applications, improperly closed files have few real
consequences, and the carefully managed context of a with statement