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

标签 python regex python-3.x

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

相关文章:

java - 替换Java字符串中特定长度的子字符串

python - Pytorch 自定义损失函数与 If 语句

c# - 正则表达式匹配数字标记,但前提是不属于另一个单词的一部分

python - BeautifulSoup 和带空格的类

regex - OpenRefine:反转正则表达式

python - Pandas Dataframe 中要行的列表列表

python - 将列表的多级列表展平为单级

python - 从图片中删除颜色

python - 如何强制 sympy 提取特定的子表达式?

python - True、False、None 是 Python 3 中的关键字还是内置关键字?