Code :
fo = open("backup.txt", "r")
filedata = fo.read()
with open("backup.txt", "ab") as file :
file.write(filedata[filedata.index('happy'):] + " appending text " + filedata[:filedata.rindex('ending')])
with open("backup.txt", "r") as file :
print "In meddival : \n",file.read()
Expected Output : I noticed that every now and then I need to Google fopen all over again. happy appending text ending
Actual output : I noticed that every now and then I need to Google fopen all over again. happy endinghappy ending appending text I noticed that every now and then I need to Google fopen all over again. happy
Okay, this will definitely fix your problem.
As you can see, I am getting the index of the beginning of the
ending
word. Then, I usejoin
to make push in theappending text
betweenhappy
andending
.Note You're adding to your file another line with the changes you've made. To override the old line, replace the
a
withw
in thewith open("backup.txt", "ab")...
There are more ways for doing that
You can split the string to words, find the index of the 'ending' word and
insert
the 'appending text' before it.You can also do this one: