Insert text into a text file following specific text using Python

前端 未结 3 1552
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 16:33

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.

Th

3条回答
  •  旧时难觅i
    2021-02-10 16:51

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

提交回复
热议问题