擅长:python、mysql、java
<h3>完成后删除所有行:</h3>
<pre><code>with open('myfile.txt', 'r+') as file:
for line in file:
processLine(line)
file.truncate(0)
</code></pre>
<h3>单独移除每条线:</h3>
<pre><code>lines = open('myfile.txt').readlines()
for line in lines[::-1]: # process lines in reverse order
processLine(line)
del lines[-1] # remove the [last] line
open('myfile.txt', 'w').writelines(lines)
</code></pre>
<h3>只能保留导致异常的行:</h3>
<pre><code>import fileinput
for line in fileinput.input(['myfile.txt'], inplace=1):
try: processLine(line)
except Exception:
sys.stdout.write(line) # it prints to 'myfile.txt'
</code></pre>
<p>一般来说,正如其他人已经说过的,你想做什么是个坏主意。</p>