Skip to content
Advertisement

Python: Print next x lines from text file when hitting string

The situation is as follows:

I have a .txt file with results of several nslookups.

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 :).

First I had the following code:

#!/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()

But that only printed “Authoritative answers can be found from:” the times it was in the .txt.

The code what I have now:

#!/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. I am aware of socket.gethostbyname(“foobar.baz”) but first I want to solve this basic problem.

Thank you in advance!

Advertisement

Answer

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())

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.

Instead of the range(8) for loop, I’d actually use 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)))
Advertisement