擅长:python、mysql、java
<p><code>truncate()</code>在当前位置<em>处截断。在其文件中,强调指出:</p>
<blockquote>
<p>Resize the stream to the given size in bytes <strong>(or the current position if size is not specified)</strong>.</p>
</blockquote>
<p>在<code>read()</code>之后,当前位置是文件的结尾。如果要用相同的文件句柄进行截断和重写,则需要执行<code>seek(0)</code>以移回开头。</p>
<p>因此:</p>
<pre><code>raw = open(file, "r+")
contents = raw.read().split("\n")
raw.seek(0) # <- This is the missing piece
raw.truncate()
raw.write('New contents\n')
</code></pre>
<p>(您也可以传递<code>raw.truncate(0)</code>,但这会将指针(以及以后写入的位置)留在文件开头以外的位置,当您在该位置开始写入文件时使文件变得稀疏)。</p>