如果 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)

输入.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。检查当前行,如果是要检查的行,请添加换行符。

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

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

前任:

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

相关内容

  • 没有找到相关文章

最新更新