<p>我建议在打开文件对象时使用<a href="https://docs.python.org/3.4/reference/compound_stmts.html#with" rel="nofollow noreferrer">^{<cd1>}</a>语句,这样就不需要显式关闭文件,当缩进块退出时,它将自动关闭。<br/>
通过使用<a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a>并选择适当的行,可以从一个文件中读取和过滤结果,并将结果写入另一个文件(而不是覆盖同一个文件),从而提供更简洁的方式来完成任务:</p>
<pre><code>with open("033117.txt", 'rt') as inputf, open("result.txt", 'wt') as outputf:
lines_to_write = [line for line in inputf if line.split()[0] in ("hfus", "ious", "oaus")]
outputf.writelines(lines_to_write)
</code></pre>
<hr/>
<p>如果要覆盖该文件而不是打开新的附加文件并对其进行写入,请执行以下操作:</p>
<pre><code>with open('033117.txt', 'r+') as the_file:
lines_to_write = [line for line in the_file if line.split()[0] in ("hfus", "ious", "oaus")]
the_file.seek(0) # just to be sure you start from the beginning (but it should without this...)
the_file.writelines(lines_to_write)
the_file.truncate()
</code></pre>
<p>打开模式见<a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow noreferrer">open, modes</a>。你知道吗</p>