擅长:python、mysql、java
<p>见<a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="noreferrer">docs.python.org</a>:</p>
<blockquote>
<p>When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.</p>
</blockquote>
<p>因此,将<code>close()</code>优雅地与<code>try/finally</code>一起使用:</p>
<pre><code>f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
</code></pre>
<p>这确保了即使<code># do stuff with f</code>引发异常,<code>f</code>仍将正确关闭。</p>
<p>注意<code>open</code>应该出现在<code>try</code>的</em>外部。如果<code>open</code>本身引发异常,则文件未打开,无需关闭。此外,如果<code>open</code>引发异常,则其结果是<em>没有</em>分配给<code>f</code>,并且调用<code>f.close()</code>是错误的。</p>