如果 findall 找到搜索模式,则在文件中插入新行

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

我想在 findall 找到搜索模式后向文件添加新行。我使用的代码只将输入文件的内容写入输出文件。它不会向输出文件添加新行。我该如何修复我的代码?

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

想要output.txt:

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

Added new line

this is very valuable
finish

尝试遍历每一行并检查您的文本是否存在。

例如:

res = []
with open(filename, "r") as infile:
    for line in infile:
        if line.strip() == "Hi! How are you?":
            res.append(line.strip())
            lineVal = (next(infile)).strip() 
            if lineVal == "Can you hear me?":
                res.append(lineVal)
                res.append("\n Added new line \n")
        else:
            res.append(line.strip())



with open(filename1, "w") as out_file:
    for line in res:
        out_file.write(line+"\n")

输出:

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

 Added new line 

this is very valuable
finish

这是你想要的吗:

text = "Can you hear me?"
with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for idx,line in enumerate(readcontent):
       if line.rstrip() == text:
           line+='\nAdded new line\n\n'
       out_file.write(line)

output.txt 看起来像:

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

Added new line

this is very valuable
finish

这里不用regex。检查当前行,如果是要检查的行,则添加一个换行符。

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

如果您本身需要 regex,请执行以下操作(尽管我绝不会推荐):

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