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

2024/7/2 15:08:50

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/pythonfile = 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/pythonfile = 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!

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 islicewith open('/tmp/results_nslookup.txt', 'r') as f:for line in f:if line == 'Non-authoritative answer:\n':print(''.join(islice(f, 8)))
https://en.xdnf.cn/q/73248.html

Related Q&A

Writing to a Google Document With Python

I have some data that I want to write to a simple multi-column table in Google Docs. Is this way too cumbersome to even begin attempting? I would just render it in XHTML, but my client has a very spec…

Numpy/ Pandas/ Matplotlib taking too long to install

Ive decided to install of MacOs Big Sur and now I do have to reinstall all the packages again... But Im facing some problems. I dont have much experience using terminal, but it is taking too long to in…

Tkinter messagebox not behaving like a modal dialog

I am using messagebox for a simple yes/no question but that question should not be avoided so I want to make it unavoidable and it seems if I have one question box.messagebox.askyesno("text",…

Cannot redirect when Django model class is mocked

I have a view here which adds a new List to the database and redirects to the List page. I have get_absolute_url configured in the model class. It seems to works perfectly.def new_list(request):form = …

How to make a Pygame Zero window full screen?

I am using the easy-to-use Python library pgzero (which uses pygame internally) for programming games.How can I make the game window full screen?import pgzrunTITLE = "Hello World"WIDTH = 80…

Check if one series is subset of another in Pandas

I have 2 columns from 2 different dataframes. I want to check if column 1 is a subset of column 2.I was using the following code:set(col1).issubset(set(col2))The issue with this is that if col1 has onl…

How to change the head size of the double head annotate in matplotlib?

Below figure shows the plot of which arrow head is very small...I tried below code, but it didnot work... it said " raise AttributeError(Unknown property %s % k) AttributeError: Unknown propert…

Passing a firefox profile to remote webdriver firefox instance not working

Im trying to start up a remote webdriver instance of Firefox and pass in a profile.profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.folderList","2") sel…

Tensorflow 2.3.0 does not detect GPU

The tensorflow does not detect the GPU card. I have following the procedures suggest at Nvidia website and tensorflow/install/gpu. How can I fix it? I am using the following packages and drives: NVIDI…

How to create dict from class without None fields?

I have the following dataclass:@dataclass class Image:content_type: strdata: bytes = bid: str = ""upload_date: datetime = Nonesize: int = 0def to_dict(self) -> Dict[str, Any]:result = {}if…