代码:
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。快乐 append 文本结尾
实际输出: 我注意到我时不时需要重新 Google fopen。 happy endinghappy ending appending text 我注意到我时不时需要谷歌重新打开。快乐
请您参考如下方法:
好的,这一定会解决您的问题。
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 单词开头的索引。 然后,我使用 join 在 happy 和 ending 之间的 appending text 中进行推送。
注意 您正在向您的文件添加另一行您所做的更改。要覆盖旧行,请将 中的 a 替换为 w with open("backup.txt", "ab")...
还有更多方法可以做到这一点
您可以将字符串拆分为单词,找到“结束”单词的索引并在其之前插入“append 文本”。
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)
