0

Here is the content of my file

enter image description here

I want to replace all occurrence of pyt_batch_id with any number but not the first occurrence.

I tried the below method and it is working as expected but I don't think this the best approach.

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()

output :-

enter image description here

Could anyone please suggest other alternative methods?

Found similar question but that is for a line not for file. How to replace all occurences except the first one?

Vasudha Dixit
  • 377
  • 8
  • 21
  • 2
    Does this answer your question? [How to replace all occurences except the first one?](https://stackoverflow.com/questions/32422431/how-to-replace-all-occurences-except-the-first-one) – Adam.Er8 Nov 11 '19 at 14:35
  • @Adam.Er8 Before asking the question I have visited that page but that solution would not work with the file. – Vasudha Dixit Nov 11 '19 at 15:20

0 Answers0