擅长:python、mysql、java
<p>您可以使用<a href="http://www.python.org/doc//current/library/contextlib.html#contextlib.closing">contextlib.closing</a>,例如:</p>
<pre><code>from contextlib import closing
with closing(tarfile.open('/dir/dir/dir.tar.gz', 'w:gz')) as fl:
fl.add('/dir/dir/dir/', arcname = '/')
</code></pre>
<p>来自文档:</p>
<blockquote>
<p>Even if an error occurs, <code>page.close()</code> will be called when the with block is exited.</p>
</blockquote>
<p><code>contextlib.closing</code>自Python2.5(或者更早的版本)以来就可用了。</p>