2016-07-14 50 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 
相关问题