title: How to replace all occurrence of a string in file except the first occurrence using Python?
body: <p>Here is the content of my file</p>
  
  <p><a href="https://i.stack.imgur.com/H3haX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H3haX.png" alt="enter image description here"></a></p>
  
  <p>I want to replace all occurrence of <strong>pyt_batch_id</strong> with any number but not the first occurrence.</p>
  
  <p>I tried the below method and it is working as expected but I don't think this the best approach.</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>output :-</p>
  
  <p><a href="https://i.stack.imgur.com/eCsqg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eCsqg.png" alt="enter image description here"></a></p>
  
  <p>Could anyone please suggest other alternative methods?</p>
  
  <p>Found similar question but that is for a line not for file.
  <a href="https://stackoverflow.com/questions/32422431/how-to-replace-all-occurences-except-the-first-one">How to replace all occurences except the first one?</a></p>