擅长:python、mysql、java
<p>如果您使用的是python 2.5+,则可以使用<code>with</code>关键字(尽管2.5需要'from<strong>future</strong>import with_语句)</p>
<pre><code>with open('filename.txt', 'r') as f:
#do stuff here
pass
#here f has been closed and disposed properly - even with raised exceptions
</code></pre>
<p>我不知道破坏<code>with</code>语句需要什么样的灾难性失败,但我认为这是一个非常糟糕的失败。在WinXP上,我的快速非科学测试:</p>
<pre><code>import time
with open('test.txt', 'w') as f:
f.write('testing\n')
while True:
time.sleep(1)
</code></pre>
<p>然后用Windows任务管理器终止进程,仍然将数据写入文件。</p>