Christoph N Christoph N - 1 year ago 84
Python Question

Python Get column width from headline

I have a table like output and I would like to get the input from each line separated by column.
Unfortunately the column does not always have the same width and there can be whitespaces inside the column.
But the column always starts at the position of the description in the headline and ends 1 field before the next headline.
My idea was to get the position of the words in the headline and then split the line with something like

var = line[firstword:secondword-1]
var2 = line[secodword:thirdword-1]

Port Name Status Vlan Duplex Speed Type
Eth1/1 Server1 connected 1 full 10G 10Gbase-SR
Eth1/2 Server 2 notconnec 1234 full 10G SFP-1000BAS
Eth1/3 That is poss err-disab trunk full 10G 10Gbase-SR


How can I get this positions?

Answer Source

If you know the column headers, you can do something like this (assuming variable lines contains the table:

indices = [lines[0].index(header) for header in ["Port", "Name", "Status", "Vlan", "Duplex", "Speed", "Type"]]

If you don't, then assuming the headers don't contain whitespace (similarly to as Karmanya Aggarwal already suggested):

indices = [lines[0].index(header) for header in [w for w in lines[0].split(" ") if w != ""]]

Or using a regex: indices = [lines[0].index(header) for header in [w for w in re.split(r"\s+", lines[0])]]

Now you can get the column values using the indices:

lines[1][indices[1]:indices[2]].strip()
# -> Server1

Of course, if the table is actually tab-separated, you'll want to use the csv module instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download