我正在创建一个脚本,我在其中查找文件中的特定字符串,然后打印接下来的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))
答案 0 :(得分: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