Search text file and insert line

前端 未结 3 1365
长发绾君心
长发绾君心 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:06

    You could use

    f = open("file.txt","rw")
    lines = f.readlines()
    for i in range(len(lines)):
         if lines[i].startswith("Text2"):
                lines.insert(i+3,"Inserted text") #Before the line three lines after this, i.e. 2 lines later.
    
    print "\n".join(lines)
    
    0 讨论(0)
  • 2021-01-15 06:23

    If you load the file contents into a list, it would be easier to manipulate:

    searchline = 'Text4'
    lines = f.readlines() # f being the file handle
    i = lines.index(searchline) # Make sure searchline is actually in the file
    

    Now i contains the index of the line Text4. You can use that and list.insert(i,x) to insert before:

    lines.insert(i, 'Random text to insert')
    

    Or after:

    lines.insert(i+1, 'Different random text')
    

    Or three lines after:

    lines.insert(i+3, 'Last example text')
    

    Just make sure to include error handling for IndexErrors and you can do with that whatever you want.

    0 讨论(0)
  • 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,
    
    0 讨论(0)
提交回复
热议问题