<p>你在找这样的东西吗?在</p>
<pre><code>def remove_line_from_file(filename, line_number):
with open(filename) as f:
lines = f.readlines()
lines[line_number - 1] = '\n' # <- or whatever kind of newline is relevant for your system
with open(filename, 'w') as f:
f.writelines(lines)
</code></pre>
<p>那么,如果文件<code>test</code>的内容是</p>
^{pr2}$
<p>运行<code>remove_line_from_file('test', 2)</code>将把<code>test</code>变成</p>
<pre><code>line 1
line 3
</code></pre>
<p>更新,现在我已经正确地阅读了这个问题:这个方法在适当的地方修改文件,用空白字符替换行的内容:</p>
<pre><code>def remove_line_from_file(filename, line_number):
with open(filename, 'r+') as f:
count = 0
bytes_read = 0
while True:
bytes_read += 1
this_byte = f.read(1)
if not this_byte:
break
if this_byte == '\n':
count += 1
if count == line_number - 1:
start = bytes_read
elif count == line_number:
f.seek(start)
f.write(' ' * (bytes_read - start - 1))
break
</code></pre>
<p>根据pm2ring上面的评论,使用<code>chr(127)</code>代替{<cd5>}也是有意义的。在</p>