Python:命中字符串时从文本文件中打印下x条线 [英] Python: Print next x lines from text file when hitting string
问题描述
情况如下:
我有一个.txt文件,其结果是多个nslookups.
I have a .txt file with results of several nslookups.
我想循环tru文件,并在每次命中字符串非权威性答案:"时,脚本必须从该位置 打印以下8行.如果可以,我应该在屏幕上获得所有积极的结果:).
I want to loop tru the file and everytime it hits the string "Non-authoritative answer:" the scripts has to print the following 8 lines from that position. If it works I shoud get all the positive results in my screen :).
首先,我有以下代码:
#!/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中的时间.
But that only printed "Authoritative answers can be found from:" the times it was in the .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()
但是,当我运行它时,它会很好地将第一个结果打印到我的屏幕上,但不会打印其他正向结果.
But when I run it, it prints the first result nicely to my screen but does not print the other positve results.
p.s.我知道socket.gethostbyname("foobar.baz"),但首先我想解决这个基本问题.
p.s. I am aware of socket.gethostbyname("foobar.baz") but first I want to solve this basic problem.
提前谢谢!
推荐答案
您可以将该文件用作迭代器,然后在每次找到句子时打印接下来的8行:
You can use the file as an iterator, then print the next 8 lines every time you find your sentence:
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
循环中循环),它将返回该文件的下一行,直到您读取了最后一行.
Each time you use the next()
function on the file object (or loop over it in a for
loop), it'll return the next line in that file, until you've read the last line.
实际上,我会使用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)))
这篇关于Python:命中字符串时从文本文件中打印下x条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!