Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is the content of my file

batch_rollback.txt
------------------------------
pyt_batch_id :- pyt_batch_id

Here multilines of
sql statements
the main pyt_batch_id
task is to
replace pyt_batch_id
from its second
pyt_batch_id occurence
-----------------------------------------

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.

output :-

pyt_batch_id :- 123456

Here multilines of
sql statements
the main 123456
task is to
replace 123456
from its second
123456 occurence


Could anyone please suggest other alternative methods?

What I have tried:

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()
Posted
Updated 11-Nov-19 5:06am

1 solution

There is no need to write the interim file, try:
Python
oldtext = open("BATCH_ROLLBACK.txt").read()
oldtext = oldtext.replace('pyt_batch_id', '123456')
newtext = oldtext.replace('123456', 'pyt_batch_id',1)

f2 = open('NEWBATCH_ROLLBACK.txt', 'w')
f2.write(newtext)
f2.close()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900