这是我文件的内容
我想用任何数字代替所有出现的 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()
输出:-
有人可以建议其他替代方法吗?
发现了类似的问题,但这是针对行而不是文件。 How to replace all occurences except the first one?