2017-06-05 77 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