Python:在击中字符串时从文本文件中打印下一行x行

Mob*_*eep 5 python linux

情况如下:

我有一个.txt文件,其中包含几个nslookups的结果.

我想循环文件,并且每次遇到字符串"非权威性答案:"脚本必须从该位置打印以下8行.如果它工作,我应该在我的屏幕上得到所有积极的结果:).

首先,我有以下代码:

#!/bin/usr/python

file = open('/tmp/results_nslookup.txt', 'r')
f = file.readlines()

for positives in f:
        if 'Authoritative answers can be found from:' in positives:
                print positives
file.close()
Run Code Online (Sandbox Code Playgroud)

但是那只印刷了"权威性答案可以从:"它在.txt中的时间.

我现在的代码:

#!/bin/usr/python

file = open('/tmp/results_nslookup.txt', 'r')
lines = file.readlines()

i = lines.index('Non-authoritative answer:\n')

for line in lines[i-0:i+9]:
        print line,

file.close()
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它会很好地将第一个结果打印到我的屏幕上,但不打印其他正面结果.

ps我知道socket.gethostbyname("foobar.baz"),但首先我要解决这个基本问题.

先感谢您!

Mar*_*ers 6

您可以将该文件用作迭代器,然后在每次找到您的句子时打印接下来的8行:

with open('/tmp/results_nslookup.txt', 'r') as f:
    for line in f:
        if line == 'Non-authoritative answer:\n':
            for i in range(8):
                print(next(lines).strip())
Run Code Online (Sandbox Code Playgroud)

每次在文件对象上使用该next()函数(或在循环中循环它for)时,它将返回该文件中的下一行,直到您读完最后一行.

而不是range(8)for循环,我实际上使用itertools.islice:

from itertools import islice

with open('/tmp/results_nslookup.txt', 'r') as f:
    for line in f:
        if line == 'Non-authoritative answer:\n':
            print(''.join(islice(f, 8)))
Run Code Online (Sandbox Code Playgroud)