gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:56 24 4
gpt4 key购买 nike

代码:

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 单词开头的索引。然后,我使用 joinhappyending 之间的 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)

关于python - 我想在文件中的 2 个字符串之间添加一个字符串,但在输出中整个文本被 append 在文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com