【发布时间】:2018-12-10 07:56:21
【问题描述】:
我想在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
【问题讨论】:
-
基本上,您需要在每个“你能听到我的声音吗?”之后换行。 ?
-
只有一行“你能听到我说话吗?”在输入文件中。所以在那之后我只需要一个新行。
-
一行或多行,
regex在这里似乎有点矫枉过正。 -
@klutt 实际输出类似于所需的输出。正如我之前所说,我需要使用
findall在输入文件中查找多行。实际输入更复杂。
标签: python regex python-3.x python-2.7 findall