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
endingword. Then, I usejointo make push in theappending textbetweenhappyandending.Note You're adding to your file another line with the changes you've made. To override the old line, replace the
awithwin 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
insertthe 'appending text' before it.You can also do this one: