<p>在python中,<code>with</code>关键字用于处理非托管资源(如文件流)。它类似于VB.NET和C中的<code>using</code>语句。它允许您确保在使用资源的代码完成运行时“清理”该资源,即使抛出异常。它为<code>try/finally</code>块提供“语法糖”。</p>
<p>来自<a href="http://docs.python.org/whatsnew/2.6.html#pep-343-the-with-statement" rel="noreferrer">Python Docs</a>:</p>
<blockquote>
<p>The <code>with</code> statement clarifies code that previously would use <code>try...finally</code> 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.</p>
<p>The <code>with</code> statement is a control-flow structure whose basic structure is:</p>
<pre><code>with expression [as variable]:
with-block
</code></pre>
<p>The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has <code>__enter__()</code> and <code>__exit__()</code> methods).</p>
</blockquote>
<p><em>更新</em>根据Scott Wisniewski的评论修复了VB标注。我确实把<code>with</code>和<code>using</code>搞混了。</p>