pythonpython-3.xlistciscoconfparse

Split a list on a key word which may appear multiple times


I've read the examples which seem similar but I am not at that level to understand the answers. I want to take the list output and write each interface as a separate line (aka list I write to a csv). I need to split the initial return list on the keyword 'interface Vlan*'

I want to split returned list vlanlist on keyword interface vlan* into separate lists

from ciscoconfparse import CiscoConfParse
import os

for filename in os.listdir():
    if filename.endswith(".cfg"):
        p = CiscoConfParse(filename)
        vlanlist=(p.find_all_children('^interface Vlan'))
        vlanlist.insert(0,filename)

        print(vlanlist) 

This is one line of output. I need to split the list on keyword "interface vlanxxx" into separate lines

[ 'interface Vlan1', ' no ip address', ' shutdown', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

Desired OUTPUT (this may have 2-20 diferent interfaces I want to split on depending on config file)

['interface Vlan1' ' no ip address', ' shutdown']
['interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

Solution

  • You can further separate your returned vlanlist before you append the file names:

    # First, find the index in the list where "interface Vlan" exists:
    # Also, append None at the end to signify index for end of list
    indices = [i for i, v in enumerate(l) if v.startswith('interface Vlan')] + [None]
    
    # [0, 3, None]
    
    # Then, create the list of lists based on the extracted indices and prepend with filename
    newlist = [[filename] + vlanlist[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
    
    for l in newlist: print(l)
    
    # ['test.cfg', 'interface Vlan1', ' no ip address', ' shutdown']
    # ['test.cfg', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']
    

    Explanation for the second list comprehension:

    newlist = [
        [filename] +                   # prepend single-item list of filename
        vlanlist[                      # slice vlanlist
            indices[i]:                # starting at the current index
            indices[i+1]               # up to the next index
        ] 
        for i in range(len(indices)-1) # iterate up to the second last index so i+1 doesn't become IndexError
    ]
    

    If you don't like the index approach, you can try zip instead:

    lists = [[filename] + vlanlist[start:end] for start, end in zip(indices[:-1], indices[1:])]