file_path = 'data/table.txt'
with open(file_path) as f:
content = f.readlines()
# it removes the empty lines
clean_content = [l for l in content if l != '\n']
# remove the line terminator for each line
lines = [l.replace('\n', '') for l in clean_content]
# attributes of the dictionary
dict_attrs = lines[0].split()
interfaces = [dict(zip(dict_attrs, l.split())) for l in lines[1:]]
interfaces_up = [i for i in interfaces if i['State'] == 'Up']
迭代第二行中的行(使用
next
),检查state是否为Up并附加它们(或执行您想做的任何事情)。在输出:
^{pr2}$顺便说一句,即使你不使用
next
,也没关系。在考虑到您的数据包含在}的接口
data/table.txt
中,这里的代码以结构化的方式提取内容,并只过滤出{结果:
[{'VLan': 'Vlan1', 'Interface': 'Fa0/0', 'State': 'Up'}, {'VLan': 'Vlan3', 'Interface': 'Fa0/3', 'State': 'Up'}]
相关问题 更多 >
编程相关推荐