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

最佳答案

首次尝试:

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

关于python - 查找以下行中特定字符串之后是否存在特定字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38385274/

10-11 22:42
查看更多