简体   繁体   中英

Python read append more that one line to a list from a text file

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.

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

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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM