<p>你想做的事在任何语言中都是不实际的。</p>
<p>首先,正如其他人所说,文件对象上没有<code>replace()</code>方法。</p>
<p>更重要的是你似乎不明白文本文件是如何工作的。你说:“<em>每当他们创建一个新文件时,我都看到一些答案。”。你考虑过他们为什么这么做吗?</p>
<p><em>“我只需要将+1添加到特定行”</em></p>
<p>让我们在文本文件中取几行,您认为<em>看起来像这样:</p>
<pre><code>onetwomumble9
threefourmumble3
</code></pre>
<p>但是文本文件没有什么特别的,它只是从第一个字节到最后一个字节,换行显示行的结束位置。看起来真的是这样:</p>
<pre><code>onetwomumble9\nthreefourmumble3\n
</code></pre>
<p>其中,<code>\n</code>表示单个换行符。</p>
<p>假设你用<code>10</code>替换了<code>9</code>,用<code>4</code>替换了<code>3</code>。问题是<code>10</code>比<code>9</code>宽,额外的字符将覆盖后面的换行符(或任何其他字符)。所以你的结局是:</p>
<pre><code>onetwomumble10threefourmumble4\n
</code></pre>
<p>你输了!</p>
<p>这就是为什么你必须复制文件来更新它!另一种方法是使用处理这些问题的数据库(如SQLite)。</p>
<p>有一些解决办法。最简单的方法是确定字符的绝对最大数量,并用零填充,例如<code>0009</code>将更新为<code>0010</code>。</p>
<p>假设文件如下所示:</p>
<pre><code>onetwomumble0009
threefourmumble0005
sixsevenmumble0067
eightnonemumber0042
</code></pre>
<p>对于同一个文件的读写,必须自己维护文件的位置。当你读一行时,它把当前的位置放在下一行,所以要重写一行,你必须把它移回去。
示例代码:</p>
<pre><code>import re
import sys
# Could be done as a one-line lambda, but would be difficult to read
def addit(m):
num = m.groups()[0]
new_num = "%04d" % (int(num) + 1)
return new_num
line_number = 1
with open('gash.txt', 'r+') as uf:
while True:
start_pos = uf.tell() # Get start of line position
line = uf.readline()
if not line : break
end_pos = uf.tell() # Get end of line position - needed if updating more than one line
# Let's say we update line 2, and we decided on 4 chars
if line_number == 2:
# Do the add
newline = re.sub(r'(\d{4})$', addit, line)
# Sanity check
if len(newline) != len(line):
print("line length changed!", line, file=sys.stderr)
sys.exit(1)
# Seek to start of line just read and write
uf.seek(start_pos)
uf.write(newline)
# Seek to start of next line
uf.seek(end_pos)
# If we only wanted to update one line, we can:
break
line_number += 1
</code></pre>