This question already has answers here:
Writing a list to a file with Python
                                
                                    (18个回答)
                                
                        
                                2年前关闭。
            
                    
关于上一个问题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匹配并保持原始格式正确?

最佳答案

你可以用

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

10-06 07:10