Reputation: 37
I have a text file of a network device configuration and I have my scrip loops through the lines of the file and here is what I'm looking for:
I would like to have my script append to a list if it finds a specific word in the line. so far I'm only able to append one single line to my list...here is an example:
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith ("show license verbose"):
license.append(line)
print license
so far it only gets me that one single line with "show license verbose". and I want it to get me say 5 more line after that phrase is found.
Thanks.
Upvotes: 0
Views: 200
Reputation: 502
open returns a generator therefore you might be able to use next method:
# you don't need this input as you already has generator
source = ['a','b','c','d','e','f','g','h','i','j']
# turn it to generator
g = (i for i in source)
# create empty list
lines = []
# put what you want inside
for item in g:
if item=='c': # this can be replaced with .startswith()
lines.append(item)
for i in range(4):
lines.append(next(g))
In : lines
Out: ['c', 'd', 'e', 'f', 'g', 'h']
Upvotes: 1
Reputation: 78536
You can use itertools.islice
to fetch succeeding lines from the file object:
from itertools import islice
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith("show license verbose"):
license.append(line)
license.extend(islice(my_file, 5))
print license
Upvotes: 2
Reputation: 1441
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith ("show license verbose"):
license.append(line)
for (i, line) in zip( range(1, 6), my_file ):
license.append( line )
print( license )
It's python3 code for python 2 you probably will want to remove brackets in last print and use xrange
instead of range
Upvotes: 2