gpt4 book ai didi

python - 使用 Python 将文本插入到特定文本之后的文本文件中

转载 作者:太空狗 更新时间:2023-10-30 02:04:58 25 4
gpt4 key购买 nike

我必须编辑一些文本文件以包含新信息,但我需要根据周围的文本将该信息插入文件中的特定位置。

这不符合我的要求:

 with open(full_filename, "r+") as f:
lines = f.readlines()
for line in lines:
if 'identifying text' in line:
offset = f.tell()
f.seek(offset)
f.write('Inserted text')

...因为它将文本添加到文件末尾。我如何将它写到识别文本之后的下一行?

(AFAICT,这不是类似问题的重复,因为没有一个能够提供这个答案)

最佳答案

如果您不需要在原地工作,那么可能是这样的:

with open("old.txt") as f_old, open("new.txt", "w") as f_new:
for line in f_old:
f_new.write(line)
if 'identifier' in line:
f_new.write("extra stuff\n")

(或者,与 Python-2.5 兼容):

f_old = open("old.txt")
f_new = open("new.txt", "w")

for line in f_old:
f_new.write(line)
if 'identifier' in line:
f_new.write("extra stuff\n")

f_old.close()
f_new.close()

轮流

>>> !cat old.txt
a
b
c
d identifier
e

进入

>>> !cat new.txt
a
b
c
d identifier
extra stuff
e

(关于在“string2”中使用“string1”的常见警告:“enamel”中的“name”为 True,“Othello”中的“hello”为 True,等等,但显然你可以使条件任意复杂。)

关于python - 使用 Python 将文本插入到特定文本之后的文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709864/

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