如何使用Python替换文件中所有出现的字符串(除了第一次出现的字符串)?

时间:2019-11-11 14:32:24

标签: python-3.x

这是我文件的内容

enter image description here

我想用任何数字代替所有出现的 pyt_batch_id ,而不是第一个出现。

我尝试了下面的方法,它按预期工作,但我认为这不是最好的方法。

s = open("BATCH_ROLLBACK.txt").read()
s = s.replace('pyt_batch_id', '123456')
f = open("BATCH_ROLLBACK.txt", 'w')
f.write(s)
f.close()

f2 = open('BATCH_ROLLBACK.txt', 'r')
contents = f2.read().replace('123456', 'pyt_batch_id',1)
f2.close()
f2 = open('BATCH_ROLLBACK.txt', 'w')
f2.write(contents)
f2.close()

输出:-

enter image description here

有人可以建议其他替代方法吗?

发现了类似的问题,但这是针对行而不是文件。 How to replace all occurences except the first one?

0 个答案:

没有答案