在文本文件中替换字符串、整数、浮点数

-4 投票
1 回答
2034 浏览
提问于 2025-04-18 17:17

好吧,我需要在一个文本文件中找到并替换特定的字符串,比如整数和浮点数。
举个例子:
如果我有这一行 conf_send = 1234
我希望结果变成这样:conf_send = 24,或者像这样 conf_send=1.1
下面的代码没有给我想要的结果:

import string
file = open ('a.txt','r')
txt = file.read()
file.close()#closing opened file
#replacing procedure
replace = string.Template(txt)
replaced = replace.substitute(envoi = 'newstring') 

当我打印结果(print replaced)时,它告诉我替换过程已经完成,但当我打开文件 a.txt 时,我发现什么都没有发生。

1 个回答

0

如果你想在一个文件中替换特定的文字,我建议你使用一个叫做 fileinput 的模块:

import fileinput

for line in fileinput.input('filename', inplace=True):
    # do what you need to do and then just print:
    print line.replace('1234', '24')

撰写回答