【问题标题】:Python - Write list to text file with \n from re.findall [duplicate]Python - 使用来自 re.findall 的 \n 将列表写入文本文件 [重复]
【发布时间】:2018-08-02 18:13:57
【问题描述】:

参考上一个问题Python Regex - Capture match and previous two lines

我正在尝试将此匹配写入文本文件,但它似乎将所有匹配写入 1 行。

尝试了这些组合,但没有成功

    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 并保持原始格式正确?

【问题讨论】:

  • myfilename.write("\n".join(output))myfilename.write("\r\n".join(output))
  • 啊,谢谢,我搜索了,但可能没有字
  • 对*谢谢。

标签: python regex python-3.x


【解决方案1】:

你可以使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2020-04-20
    • 2010-10-28
    相关资源
    最近更新 更多