gpt4 book ai didi

Python - 使用 re.findall 中的\n 将列表写入文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:22 26 4
gpt4 key购买 nike

引用上一个问题 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com