with open('somefile.txt') as my_file: # some processing my_file.close()
with open('somefile.txt') as my_file: 1/0 # raise Exception my_file.close() # Your close() call is never going to be called
with语句的__exit __()函数,因为它遵循try … except … finally模式.
The with statement is used to wrap the execution of a block with
methods defined by a context manager (see section With Statement
Context Managers). This allows common try…except…finally usage
patterns to be encapsulated for convenient reuse.
The context manager’s __exit__() method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are
passed as arguments to __exit__()
>>> with open('somefile.txt') as f: ... pass >>> f.closed # True