1

In reference to a previous question Python Regex - Capture match and previous two lines

I am try to write this match to a text file but it seems to write all the matches on 1 line.

Tried these combinations with no luck

    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

Would I need a for loop to iterate each index to a new line, or am I missing something, it should be matching the CRLLF and keep the original format correct?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
arealhobo
  • 447
  • 1
  • 6
  • 17

1 Answers1

1

You could use

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))
Jan
  • 42,290
  • 8
  • 54
  • 79