我想在文件中的 2 个字符串之间添加一个字符串,但在输出中整个文本被附加在文件末尾

I want to add a string in between of 2 strings in file, but in output whole text is getting appended at the end of file

代码:

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

预期输出: 我注意到我时不时需要重新 Google fopen。快乐附加文本结尾

实际输出: 我注意到我时不时需要重新 Google fopen。 happy endinghappy ending appending text 我注意到我时不时需要 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 单词开头的索引。 然后,我使用 joinhappyending 之间的 appending text 中进行推送。

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

中的 a 替换为 w

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

你可以将字符串拆分成单词,找到'ending'单词的索引和insert它前面的'appending text'。

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)

您需要拆分文件内容

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