вставить новую строку в файл, если findall находит шаблон поиска - PullRequest
0 голосов
/ 02 июля 2018

Я хотел бы добавить новую строку в файл после того, как 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

Ответы [ 3 ]

0 голосов
/ 02 июля 2018

Это то, что вы хотите:

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
0 голосов
/ 02 июля 2018

Не используйте 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')
0 голосов
/ 02 июля 2018

Попробуйте перебрать каждую строку и проверить, существует ли ваш текст.

Ex:

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