小编Mob*_*eep的帖子

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

情况如下:

我有一个.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"),但首先我要解决这个基本问题.

先感谢您!

python linux

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

linux ×1

python ×1