引用上一个问题 Python Regex - Capture match and previous two lines
我尝试将此匹配写入文本文件,但似乎将所有匹配写入一行。
尝试了这些组合,但没有成功
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', f.read())
myfilename.write(str(list(output) + '\n')) # gives me TypeError: can only concatenate list (not "str") to list
myfilename.write(str(output)) # writes to one line
我是否需要一个 for 循环来将每个索引迭代到新行,或者我是否遗漏了某些内容,它应该与 CRLLF 匹配并保持原始格式正确?
最佳答案
你可以使用
with open ("file_here.txt", "r") as fin, open("output.txt", "w") as fout:
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', fin.read())
fout.write("\n".join(output))
关于Python - 使用 re.findall 中的\n 将列表写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935143/