如何使用 python 覆盖文件中的字符串?

How can I over-write a string in a file using python?

所以我有一个文本文件(名为 'Numbers'),如下所示:

1 - 2 - 3 - 8 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  

我想用数字 4 替换第一行中的数字 8。 我该怎么做?
到目前为止,我得到了以下信息:

File = open('Numbers.txt','r+')  
for line in File:
  Row = line.split(' - ')
  FourthValue = Row[3]
  NewFourthValue = '4'
  NewLine = line.replace(FourthValue,NewFourthValue)
  File.write(NewLine)
  break
File.close()

然后,它将新的正确行附加到文件末尾,如下所示:

1 - 2 - 3 - 8 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 6  
1 - 2 - 3 - 4 - 5 - 61 - 2 - 3 - 4 - 5 - 6

我该怎么做才能让这个新行替换第一行?

文本文件重写有问题,因为它们通常有可变长度的记录,而你的是固定长度的,所以:

fh = open('gash.txt','r+') 

# read the first line
line = fh.readline()
row = line.split(' - ')
fourthValue = row[3]

newFourthValue = '4'
newLine = line.replace(fourthValue, newFourthValue)

此时"current file position"在行的开头,所以我们必须将它移回当前记录的开头

fh.seek(0)
fh.write(newLine)

fh.close()

这很简单。该行是问题是第一行。如果它在其他任何地方,我们将不得不使用 fh.tell() 记住每一行之前的文件位置,然后在 fh.seek().

中使用该数字

编辑: 在回答问题 "If I wanted to replace a value in the 4th line not the first" 时,这会将第四行的 4 替换为 8。

lineToChange = 4
fieldToChange = 3
newValue = '8'
sep = ' - '
lineno = 0

fh = open('gash.txt','r+')

while True:
    # Get the current file position
    start_pos = fh.tell()

    # read the next line
    line = fh.readline()
    if not line: break          # exit the loop at EOF

    lineno += 1

    if lineno == lineToChange:
        row = line.split(sep)

        # A different replace mechanism
        row[fieldToChange] = newValue
        newLine = sep.join(row)

        # before writing, we must move the file position
        fh.seek(start_pos)
        fh.write(newLine)

fh.close()

请注意这只有效,因为我们正在用另一个单个字符替换单个字符。如果我们想用 10 替换 8 那么这将不起作用,因为现在行长度会不同并且我们会覆盖下一行的开头。

阅读第一行后,您需要 "rewind" 文件以便覆盖第一行。

with open(fname, 'r+') as f:
    row = f.readline()
    row = row.replace('8', '4')
    f.seek(0)
    f.write(row)

执行此操作时要小心,因为如果新数据与旧数据不完全相同大小,您将弄乱以下行。通常,创建一个新文件、将(可能修改过的)行从一个文件复制到另一个文件要简单和安全得多,但是如果您必须处理大文件,了解这种技术是很好的。

FWIW,我的回答 here 处理文件中任意位置的数据就地修改的更一般情况。