擅长:python、mysql、java
<p>Python不会在每次<code>write</code>之后刷新文件。您要么需要使用<a href="http://docs.python.org/2/library/stdtypes.html#file.flush" rel="noreferrer">^{<cd2>}</a>手动刷新它:</p>
<pre><code>>>> f.flush()
</code></pre>
<p>或者用<a href="http://docs.python.org/2/library/stdtypes.html#file.close" rel="noreferrer">^{<cd3>}</a>关闭它:</p>
<pre><code>>>> f.close()
</code></pre>
<p>在实际程序中使用文件时,建议使用<code>with</code>:</p>
<pre><code>with open('some file.txt', 'w') as f:
f.write('some text')
# ...
</code></pre>
<p>这将确保文件将被关闭,即使抛出异常。不过,如果您想在REPL中工作,您可能需要坚持手动关闭它,因为它会在尝试执行之前尝试读取<code>with</code>的全部内容。</p>