如何在python中拆分文本文件中的表?

2024-09-29 21:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设文件中有一个表:

VLan    Interface       State

Vlan1       Fa0/0       Up

Vlan2       Fa0/1       Down

Vlan3       Fa0/3       Up

现在我实际上需要获取状态为up的VLan接口的名称。 但首先我得把桌子分开。 我是python新手,不知道如何拆分这个表。在


Tags: 文件名称状态interfacedownstateup桌子
2条回答

迭代第二行中的行(使用next),检查state是否为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)

输出:

^{pr2}$

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

考虑到您的数据包含在data/table.txt中,这里的代码以结构化的方式提取内容,并只过滤出{}的接口

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

相关问题 更多 >

    热门问题