Python - 跳过空行并在匹配后打印 3 行

Python - skip empty lines and print 3 lines after a match

我好像不能跳过空行-

import re  

with open('list.txt', 'r+') as f:
      line = f.readline()
      while(line):
        if line != ['']: 
            if " win" in line:
                print(f.readline(),end="")
            # 2nd line
                print(f.readline(),end="")
            # 3rd line
                print(f.readline(),end="")
            line = f.readline()

list.txt

You tell yourself...
That should have been my big win.

It's a kick in the gut. 
Knowing in your heart the reason.
While you're stuck on the outside.
Grinning.

它打印如下 - 行出现在空行之后。

It's a kick in the gut. Knowing in your heart the reason.

您需要告诉它在打印时跳过空行(注释是内联的):

if " win" in line:
    for _ in range(3):  # do three times
        line = f.readline()  # get next line
        # skip blank lines
        while not line.strip():
            line = f.readline()
        # Print the non-blank line
        print(line, end="")
line = f.readline()