2017-06-05 80 views
-1

我似乎无法跳过空线 -的Python - 跳过空行和打印3行的匹配后

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. 

它打印中包含instead- 线在空行后出现。

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

+0

你到底想干什么?比赛结束后打印3条非空线? – TemporalWolf

+0

是的,比赛结束后有3条非空线 – Arif

+0

一条线可以显示为空,但是每条线都以换行符结束。在检查内容之前,你需要去掉('str.rstrip()'应该足够)你的行... – zwer

回答

0

打印时,你需要告诉它跳过空白行(注释是内联):

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() 
+0

对不起,没有工作。仍然打印空行。 – Arif

+0

我做了一个编辑...我假设你的“空白行”并不是真正的空白=> strip()将允许它只匹​​配空白行。 – TemporalWolf

+0

是的....而不是line.strip():....似乎已经解决了它。谢谢。 – Arif