如果findall找到了一个搜索模式,请在文件中插入新行

2024-05-26 16:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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)

你知道吗输入.txt地址:

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

想要的输出.txt地址:

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

Added new line

this is very valuable
finish

Tags: 文件代码textretxtyouwithline
3条回答

尝试迭代每一行,检查文本是否存在。你知道吗

例如:

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

在这里不要使用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')

这就是你想要的:

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

相关问题 更多 >

    热门问题