简体   繁体   English

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

[英]How to split a table in a text file in python?

Suppose there is a table in a file: 假设文件中有一个表:

VLan    Interface       State

Vlan1       Fa0/0       Up

Vlan2       Fa0/1       Down

Vlan3       Fa0/3       Up

Now I actually need to get the name of the VLan & Interface whose state is up. 现在,我实际上需要获取状态为VLan&Interface的名称。 But for that I need to split the table at first. 但是为此,我首先需要拆分表。 I am new to python and cannot really figure out how to split this table. 我是python新手,无法真正弄清楚如何拆分此表。

Iterate through the lines from the second line (use next for that) and check whether state is Up and append them (or do whatever you would like to do). 遍历第二行中的各行(为此使用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)

Output: 输出:

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

Btw, even if you don't use next , it is fine. 顺便说一句,即使您不使用next ,也很好。

Considering that your data is contained in data/table.txt here the code to extract the content in a structured way, and filter out only the interfaces that are Up 考虑到您的数据包含在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']

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM