0

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. 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.

Levon
  • 138,105
  • 33
  • 200
  • 191
Asish
  • 93
  • 2
  • 9

2 Answers2

2

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).

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.

Miraj50
  • 4,257
  • 1
  • 21
  • 34
0

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

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

nicor88
  • 1,398
  • 10
  • 13