I have a function that checks a .txt file and gets some data from it after analyzing it. I have a file with the name (Data.txt) which contains the below:
interface GigabitEthernet3/0/5.33
description 4543
trust upstream default
trust 8021p outbound
qos phb dscp disable
interface GigabitEthernet3/0/5.34
description 4046
trust upstream default
trust 8021p outbound
interface GigabitEthernet3/0/5.35
description 4584
trust upstream default
trust 8021p outbound
qos phb dscp disable
The below function is to extract the interfaces which don't have "qos phb dscp disable" under it. So, the final result should be saved in a file (Data with no qos.txt) with "interface GigabitEthernet3/0/5.34" in it.
What I'm asking for: I have tried to print the interface with its description, so the result will be:
interface GigabitEthernet3/0/5.34
description 4046
Can anyone help me?
def noqos(Devicess):
data = open('D:\Scripting Test/' + Devicess + '.txt').read()
def no_qos(lines):
# keep track of interfaces seen and which has qos
interfaces = []
has_qos = set()
print (Devicess + '( No qos under interfaces )')
print ("-----------------------------------------------------------")
# scan the file and gather interfaces and which have qos
for line in lines:
if line.startswith('interface'):
interface = line.strip()
interfaces.append(interface)
elif line.startswith(" qos"):
has_qos.add(interface)
# report which interfaces do not have qos
return [i for i in interfaces if i not in has_qos]
lastnoqos = open(('D:\Scripting Test/Noqos/' + Devicess + ' no qos.txt'), "w")
for interface in no_qos(data.split('\n')):
# print(interface)
# print ("\n")
lastnoqos.write(interface + '\n')
noqos('Data')
You could convert the data to a list of dictionaries and then loop through them to find the interfaces you are looking for (and perhaps do some other processing as well):
data = """interface GigabitEthernet3/0/5.33
description 4543
trust upstream default
trust 8021p outbound
qos phb dscp disable
interface GigabitEthernet3/0/5.34
description 4046
trust upstream default
trust 8021p outbound
interface GigabitEthernet3/0/5.35
description 4584
trust upstream default
trust 8021p outbound
qos phb dscp disable"""
with open('D:\Scripting Test/' + Devicess + '.txt') as textfile:
data = textfile.read()
interfaces = []
for line in data.split("\n"): # go through lines
k,_ = line.strip().split(" ",1) # get the first keyword
if k=="interface": # add a dict() for new interfaces
current = dict() # which becomes the current one
interfaces.append(current)
current[k]=line # accumulate keywords in current
for i in interfaces: # find interfaces
if "qos" not in i: # without a "qos" keyword
print(i["interface"]) # print name and description
print(i["description"])
interface GigabitEthernet3/0/5.34
description 4046