代码:

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()


预期产量:
我注意到,我不时需要重新打开Goog​​le。快乐追加文字结尾

实际输出:
我注意到,我不时需要重新打开Goog​​le。我注意到,我时不时地需要Google重新打开。快乐

最佳答案

好的,这肯定会解决您的问题。

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()


如您所见,我正在获取ending单词开头的索引。
然后,我使用joinappending texthappy之间推入ending

注意:您要在文件中添加所做更改的另一行。要覆盖旧行,请在a中将w替换为with open("backup.txt", "ab")...

有更多的方法可以做到这一点

您可以将字符串拆分为单词,找到“结尾”单词的索引,并在其前面找到insert“附加文本”。

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


您也可以执行以下操作:

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

10-07 15:19