擅长:python、mysql、java
<p>在位编辑文本文件相当困难。您的最佳选择是:</p>
<ol>
<li><p>以Unix <a href="https://en.wikipedia.org/wiki/Filter_%28Unix%29" rel="nofollow">filter</a>的形式编写程序,即在<code>sys.stdout</code>上生成新文件并使用外部工具将其放置到位</p></li>
<li><p>读入整个文件,然后在内存中构造新文件并将其写出。</p></li>
</ol>
<p>遵循第二条思路的程序如下所示:</p>
<pre><code># read transcriptions.txt into a list of lines
with open("transcriptions.txt", "r") as tFile:
inp = tFile.readlines()
# do processing and build a new list of lines
outp = []
for ln in inp:
if not to_be_deleted(ln):
outp.append(transform(ln))
# now overwrite transcriptions.txt
with open("transcriptions.txt", "w") as tFile:
tFile.writelines(outp)
</code></pre>
<p>如果您将处理位写成一个列表,那就更好了:</p>
<pre><code>outp = [transform(ln) for ln in inp
if not to_be_deleted(ln)]
</code></pre>