情况如下:
我有一个 .txt 文件,其中包含多次 nslookups 的结果。
我想循环 tru 文件,每次遇到字符串“非权威答案:”时,脚本都必须打印以下 8 行from那个位置。如果它有效,我应该在屏幕上得到所有积极的结果:)。
首先我有以下代码:
#!/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()
但是当我运行它时,它会将第一个结果很好地打印到我的屏幕上,但不会打印其他积极结果。
附注我知道 socket.gethostbyname("foobar.baz") 但首先我想解决这个基本问题。
先感谢您!
您可以将该文件用作迭代器,然后每次找到句子时打印接下来的 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()功能 https://docs.python.org/3/library/functions.html#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)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)