擅长:python、mysql、java
<p>这可能很有趣</p>
<p><a href="http://net4geeks.com/index.php?option=com_content&task=view&id=53&Itemid=11" rel="nofollow">http://net4geeks.com/index.php?option=com_content&task=view&id=53&Itemid=11</a></p>
<p>适应你的问题:</p>
<pre><code># read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("zero line\n\n")
# write the original contents
f.write(text)
f.close()
</code></pre>
<ul>
<li><p>打开文件并读取
将内容转换为“文本”。</p></li>
<li><p>关闭文件</p></li>
<li><p>重新打开参数为“w”的文件
写入</p></li>
<li><p>在文件前面写入文本</p></li>
<li><p>写出
文件到文件</p></li>
<li><p>关闭文件</p></li>
</ul>
<p>阅读链接中的警告。</p>
<p>编辑:</p>
<blockquote>
<p>But note that this isn't entirely
safe, if your Python session crashes
after opening the file the second time
and before closing it again, you will
lose data.</p>
</blockquote>