[英]Print the line after a specific line
我有一個 function 檢查 a.txt 文件並在分析后從中獲取一些數據。 我有一個名為 (Data.txt) 的文件,其中包含以下內容:
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
下面的function是提取下面沒有“qos phb dscp disable”的接口。 因此,最終結果應保存在一個文件中(Data with no qos.txt),其中包含“interface GigabitEthernet3/0/5.34”。
我要的是什么:我試圖用它的描述打印界面,所以結果將是:
interface GigabitEthernet3/0/5.34
description 4046
誰能幫我?
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')
您可以將數據轉換為字典列表,然后遍歷它們以找到您正在尋找的接口(也許還可以進行一些其他處理):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.