0

假设文件中有一个表:

VLan    Interface       State

Vlan1       Fa0/0       Up

Vlan2       Fa0/1       Down

Vlan3       Fa0/3       Up

现在我实际上需要获取状态为 up 的 VLan & Interface 的名称。但为此,我首先需要拆分表格。我是 python 新手,无法真正弄清楚如何拆分此表。

4

2 回答 2

2

遍历第二行中的行(next用于该行)并检查状态是否为Up并附加它们(或做任何你想做的事情)。

with open('test.txt','r') as f:
    next(f)
    l = [line.split()[1] for line in f if line.split()[2] == "Up"]

print(l)

输出:

['Fa0/0', 'Fa0/3']

顺便说一句,即使你不使用next,也没关系。

于 2017-11-01T12:53:39.267 回答
0

考虑到您的数据包含在data/table.txt此处,代码以结构化方式提取内容,并仅过滤掉Up

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

结果:[{'VLan': 'Vlan1', 'Interface': 'Fa0/0', 'State': 'Up'}, {'VLan': 'Vlan3', 'Interface': 'Fa0/3', 'State': 'Up'}]

于 2017-11-01T13:11:44.330 回答