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

2024-10-01 17:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个文本文件(称为“数字”),它看起来像这样:

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

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

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

我该怎么做才能让这条新生产线取代第一条生产线?你知道吗


Tags: intxt信息forlinenewline数字open
2条回答

重写文本文件是有问题的,因为它们通常有可变长度的记录,但是您的记录是固定长度的,因此:

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)

此时,“当前文件位置”位于下一行的开头,因此我们必须将其移回当前记录的开头

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

fh.close()

这太简单了。问题是第一行。如果它在其他任何地方,我们必须使用fh.tell()记住每行之前的文件位置,然后在fh.seek()中使用该数字。你知道吗

编辑: 在回答“如果我想替换第4行中的值而不是第一行中的值”的问题时,这将用第4行中的8替换4。你知道吗

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,那么这就行不通了,因为现在行长不同了,我们会覆盖下一行的开头。你知道吗

读取第一行后,您需要“倒带”文件,以便可以覆盖第一行。你知道吗

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

但在执行此操作时要小心,因为如果新数据与旧数据的大小不完全相同,则会弄乱下面的行。一般来说,创建一个新文件,将(可能修改过的)行从一行复制到另一行要简单得多&安全得多,但是如果您需要处理大型文件,了解这种技术就很好了。你知道吗

FWIW,我的答案here处理更一般的情况,即在文件中的任意位置就地修改数据。你知道吗

相关问题 更多 >

    热门问题