What is the python keyword “with” used for?
python关键字"with"用于什么?
示例来自:http://docs.python.org/tutorial/inputout.html
1 2 3 4 | >>> with open('/tmp/workfile', 'r') as f: ... read_data = f.read() >>> f.closed True |
解释:preshing from the programming在线博客P></
It’s handy when you have two related operations which you’d like to
execute as a pair, with a block of code in between. The classic
example is opening a file, manipulating the file, then
closing it:
1
2 with open('output.txt', 'w') as f:
f.write('Hi there!')The above with statement will automatically close the file after the
nested block of code. (Continue reading to see exactly how the close
occurs.) The advantage of using a with statement is that it is
guaranteed to close the file no matter how the nested block exits. If
an exception occurs before the end of the block, it will close the
file before the exception is caught by an outer exception handler. If
the nested block were to contain a return statement, or a continue or
break statement, the with statement would automatically close the file
in those cases, too.
在Python中
从Python文档:P></
The
with statement clarifies code that previously would usetry...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with statement is a control-flow structure whose basic structure is:
1
2 with expression [as variable]:
with-blockThe expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__() and__exit__() methods).
VB更新固定wisniewski' callout斯科特的评论。我真的confusing