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

时间:2018-07-02 06:30:51

标签: python regex python-3.x python-2.7 findall

我想在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 :(得分:1)

在此不使用error: cannot find symbol .setCredentials(GoogleCredentials.fromStream(serviceAccount) 。检查当前行,如果要检查的行,请添加换行符。

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

答案 1 :(得分:0)

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

例如:

fields

输出:

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

答案 2 :(得分:0)

这是您想要的吗?

List<string> toMatch = stringToMatch.Split(' ').ToList();
List<string> match = arrayOfStrings.Where(x => 
                                   !toMatch.Any(ele => !x.ToLower()
                                   .Contains(ele.ToLower())))
                                   .ToList();

$category['category'] = $this->db->where("id", $id) -> get ("category")->row(); $this->load->view("category_edit", $category); 如下所示:

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)