[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

If closure is required, though, there are two basic alternatives: the try statement’s
finally clause is the most general, since it allows you to provide general exit actions
for any type of exceptions:


myfile = open(filename, 'w')
try:
...process myfile...
finally:
myfile.close()

In recent Python releases, though, the with statement provides a more concise alterna-
tive for some specific objects and exit actions, including closing files:


with open(filename, 'w') as myfile:
...process myfile, auto-closed on statement exit...

This statement relies on the file object’s context manager: code automatically run both
on statement entry and on statement exit regardless of exception behavior. Because the
file object’s exit code closes the file automatically, this guarantees file closure whether
an exception occurs during the statement or not.


The with statement is notably shorter (3 lines) than the try/finally alternative, but it’s
also less general—with applies only to objects that support the context manager pro-
tocol, whereas try/finally allows arbitrary exit actions for arbitrary exception con-
texts. While some other object types have context managers, too (e.g., thread locks),
with is limited in scope. In fact, if you want to remember just one exit actions option,
try/finally is the most inclusive. Still, with yields less code for files that must be closed
and can serve well in such specific roles. It can even save a line of code when no
exceptions are expected (albeit at the expense of further nesting and indenting file
processing logic):


myfile = open(filename, 'w') # traditional form
...process myfile...
myfile.close()

with open(filename) as myfile: # context manager form
...process myfile...

In Python 3.1 and later, this statement can also specify multiple (a.k.a. nested) context
managers—any number of context manager items may be separated by commas, and
multiple items work the same as nested with statements. In general terms, the 3.1 and
later code:


with A() as a, B() as b:
...statements...

Runs the same as the following, which works in 3.1, 3.0, and 2.6:


with A() as a:
with B() as b:
...statements...

140 | Chapter 4: File and Directory Tools

Free download pdf