python关键字”with”用于什么?

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中withis used when the keyword(非托管资源的类文件的工作与streams)。EN is similar to the statement # usingVB.NET和C。恩,你allows确保资源是"that when the队列随访cleaned"finishes uses恩跑,甚至如果是扔了。它提供了try/finally是句法糖是for块。P></

从Python文档:P></

The with statement clarifies code that previously would use try...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-block

The 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 usingwithwith。P></