Search text file and insert line

前端 未结 3 1364
长发绾君心
长发绾君心 2021-01-15 05:56

What I want to do is (using the text below as an example), search for the string “Text2” in a text file, and then insert a line (“Inserted Text”) two lines after \"Text 2\".

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 06:26

    The quick-n-dirty way would be something like that

    before=-1
    for line in fileinput.input('file.txt', inplace=1,backup='.bak'):
        if line.startswith('Text 2'):
            before = 2
        if before == 0
            print "Inserted Text"
        if before > -1
            before = before - 1
        print line,
    

提交回复
热议问题