Issue
I have a text file regarding different information about Ip addresses after a test has been completed. I want to print out this information, how?
The text file is called "IPAddressesTEST.log"
a part of the text follows like this
Connected IPv6's:
(and here is the ipv6 address)
I've tried:
with open ('C:/test/IPAddressesTEST.log', "rt") as Ip_Log:
for l in Ip_Log:
Ip_Log_Iter = iter(l)
for lines in Ip_Log_Iter:
if lines == "Connected IPv6's:":
x = next(Ip_Log_Iter)
break
print(x)
Solution
If we assume the "IPAddressesTEST.log" looks like this:
junk
stuff
Connected IPv6's:
2345:0425:2CA1:0000:0000:0567:5673:23b5
foo
bar
Connected IPv6's:
2392:0411:2CB2:0000:0000:0567:5226:24ba
more stuff
more junk
Then the following will print out the lines immediately following a line containing the string "Connected IPv6's:"
with open('IPAddressesTEST.log', 'r', encoding='utf-8') as f:
lines = f.readlines()
for counter, line in enumerate(lines):
if "Connected IPv6's:" in line:
print(lines[counter +1].strip())
Output:
2345:0425:2CA1:0000:0000:0567:5673:23b5
2392:0411:2CB2:0000:0000:0567:5226:24ba
Edit
As requested, if you only want the first instance of Connected IPv6's
then you don't need to keep looping through the file so can break
as soon as the relevant line is found:
with open('IPAddressesTEST.log', 'r', encoding='utf-8') as f:
lines = f.readlines()
for counter, line in enumerate(lines):
if "Connected IPv6's:" in line:
print(lines[counter +1].strip())
break
Output:
2345:0425:2CA1:0000:0000:0567:5673:23b5
Notice it's just the IP address closest to the top of the file
Answered By - PangolinPaws Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.