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

2

There are 2 answers

10
boaz_shuster On BEST ANSWER

Okay, this will definitely fix your problem.

fo = open("backup.txt", "r")

filedata = fo.read()

ix = filedata.index('ending')
new_str = ' '.join([filedata[:ix], 'appending text', filedata[ix:]])

with open("backup.txt", "ab") as file:
   file.write(new_str)

with open("backup.txt", "r") as file :
   print "In meddival : \n",file.read()

As you can see, I am getting the index of the beginning of the ending word. Then, I use join to make push in the appending text between happy and ending.

Note You're adding to your file another line with the changes you've made. To override the old line, replace the a with w in the with 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.

text_list = filedata.split()
ix = text_list.index('ending')
text_list.insert(ix, 'appending text')
new_str = ' '.join(text_list)

You can also do this one:

word = 'happy'
text_parts = filedata.split('happy')
appending_text = ' '.join(word, 'appending text')
new_str = appending_text.join(text_parts)
5
farhawa On

You need to split your file content

fo = open("backup.txt", "r")

filedata = fo.read().split()

with open("backup.txt", "ab") as file:
   file.write(' '.join(filedata[filedata.index('happy'):]) + " appending text  " + ' '.join(filedata[:filedata.index('ending')]))

with open("backup.txt", "r") as file :
   print "In meddival : \n",file.read()