2016-07-14 40 views
0

我正在創建一個腳本,在該腳本中,我正在查找文件中的特定字符串,然後打印接下來的5行,但是,初始字符串可以發現在文件的其他領域,是不必要的,所以我想添加一個額外的檢查,看看下一行包含一個特定的字符串,然後打印內容如果不是,不要打印它:查找特定字符串是否存在於以下行上的特定字符串後

f = open(i, 'r') 
msg = 'somestring' 
for line in f: 
    if msg in line: # I would like to add a check if a specific (**somestring following 
        # the msg on the next line**) exists on the next line, string here 
     for string in range(5): 
      print line + ''.join(islice(f, 5)) 
+2

你能共享一個示例文件和您所需的輸出會是什麼? – smarx

+0

例如我正在查看以下字符串 說明=「」##第一行 \t ErrorCode = x; #第二行 –

+0

我的回答不適合你嗎? – smarx

回答

0

第一次嘗試:

from itertools import islice 

first_string = 'Description = "' 
second_string = 'ErrorCode' 

with open('test.txt') as f: 
    for line in f: 
     if first_string in line: 
      next_line = next(f) 
      if second_string in next_line: 
       print(next_line + ''.join(islice(f, 4))) 

的test.txt:

Description = "Something" 
FalseAlarm = true 

Description = "Something" 
ErrorCode 0 
EstimatedInstallTime = 30 
EvaluationState = 1 
Something = Else 
More = Here 

輸出:

ErrorCode 0 
EstimatedInstallTime = 30 
EvaluationState = 1 
Something = Else 
More = Here 
相關問題