5

情况如下:

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

我想循环 tru 文件,每次它遇到字符串“非权威答案:”时,脚本必须该位置打印以下 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()

但是,只有打印的“权威答案可以从:”中找到它在 .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()

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

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

先感谢您!

4

2 回答 2

7

您可以将该文件用作迭代器,然后在每次找到您的句子时打印接下来的 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())

每次您在文件对象上使用该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)))
于 2012-10-04T12:33:42.227 回答
4
file = open('/tmp/results_nslookup.txt', 'r')
for line in file:
    if line=='Non-authoritative answer:\n':
        for _ in range(8):
            print file.next()

顺便说一句:永远不要使用file变量的名称,因为它是内置函数的名称。

于 2012-10-04T12:33:52.197 回答