Search code examples
pythonregexpython-3.xpython-2.7findall

insert a new line to a file if findall finds a search pattern


I would like to add a new line to a file after findall finds a search pattern. The code I use only writes the content of the input file to the output file. It doesn't add new line to the output file. How can I fix my code?

import re
text = """
Hi! How are you?
Can you hear me?
"""
with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for line in readcontent:
    x1 = re.findall(text, line)
    if line == x1:
        line = line + text
    out_file.write(line)

Input.txt:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?
this is very valuable
finish

Desired output.txt:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?

Added new line

this is very valuable
finish

Solution

  • Use no regex here. Check current line, if it's the line to be checked, add a newline.

    with open("output.txt", "w") as out_file:
        for line in readcontent:
            out_file.write(line)
            if line.strip() == 'Can you hear me?':
                out_file.write('\n')
    

    If you need a regex itself, go for below (though I would never recommend):

    with open("output.txt", "w") as out_file:
        for line in readcontent:
            out_file.write(line)
            if re.match('Can you hear me?', line.strip()):
                out_file.write('\n')