擅长:python、mysql、java
<p>您正在从文件中读取并写入。别那样做。相反,您应该先写入一个<a href="https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile" rel="nofollow noreferrer">^{<cd1>}</a>,然后在写完并关闭原始文件后<a href="https://docs.python.org/2/library/os.html#os.rename" rel="nofollow noreferrer">^{<cd2>}</a>。在</p>
<p>或者,如果保证文件的大小很小,可以使用<code>readlines()</code>读取所有文件,然后关闭文件,修改所需的行,然后将其写回:</p>
<pre><code>def editline(file,n_line,text):
with open(file) as infile:
lines = infile.readlines()
lines[n_line] = text+' \n'
with open(file, 'w') as outfile:
outfile.writelines(lines)
</code></pre>