且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Python 在特定文本之后将文本插入到文本文件中

更新时间:2023-11-14 23:08:52

如果你不需要就地工作,那么可能是这样的:

 with open("old.txt") as f_old, open("new.txt", "w") as f_new:对于 f_old 中的行:f_new.write(line)如果标识符"在线:f_new.write("额外的东西\n")

(或者,兼容 Python-2.5):

f_old = open("old.txt")f_new = open("new.txt", "w")对于 f_old 中的行:f_new.write(line)如果标识符"在线:f_new.write("额外的东西\n")f_old.close()f_new.close()

哪个转弯

>>>!cat old.txt一种乙Cd 标识符电子

进入

>>>!cat new.txt一种乙Cd 标识符额外的东西电子

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

I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.

This doesn't work the way I need it to:

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

...in that it adds the text to the end of the file. How would I write it to the next line following the identifying text?

(AFAICT, this is not a duplicate of similar questions, since none of those were able to provide this answer)

If you don't need to work in place, then maybe something like:

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

(or, to be Python-2.5 compatible):

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

which turns

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

into

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

(Usual warning about using 'string1' in 'string2': 'name' in 'enamel' is True, 'hello' in 'Othello' is True, etc., but obviously you can make the condition arbitrarily complicated.)