擅长:python、mysql、java
<p><a href="http://docs.python.org/tutorial/inputoutput.html" rel="noreferrer">python docs</a>建议这样做:</p>
<pre><code>with open('file_to_write', 'w') as f:
f.write('file contents')
</code></pre>
<p>所以我通常就是这样做的:)</p>
<p>来自<a href="http://docs.python.org/tutorial/inputoutput.html" rel="noreferrer">docs.python.org</a>的语句:</p>
<blockquote>
<p>It is good practice to use the <strong>'with'</strong> keyword when dealing with file
objects. This has the advantage that the file is properly closed after
its suite finishes, even if an exception is raised on the way. It is
also much shorter than writing equivalent try-finally blocks.</p>
</blockquote>