charan charan - 7 months ago 9
Python Question

Python reading a file and parsing the required data

Hi I am reading a file data.txt which is in the below format.

Last table change time : 69 days, 0:17:19 ago
Number of table inserts : 93
Number of table deletes : 87
Number of table drops : 0
Number of table age-outs : 0

Port Neighbor Device ID Neighbor Port ID TTL
Et2/1 CN-Arista2 Ethernet5/1 120
Et2/2 CN-Arista2 Ethernet5/2 120
Et2/3 CN-Arista3 Ethernet5/3 120
Et2/4 CN-Arista Ethernet5/4 120
Et64/1 CN-Spine2 Ethernet64/1 120
Ma1 Arista01.Dmech.rack01 Ethernet1 120


I need out put as follows

Et2/1, CN-Arista2, Ethernet5/1
Et2/2, CN-Arista2, Ethernet5/2
Et2/3, CN-Arista3, Ethernet5/3
Et2/4, CN-Arista, Ethernet5/4
Et64/1, CN-Spine2, Ethernet64/1
Ma1, Arista01.Dmech.rack01, Ethernet1

Answer
input = """Port       Neighbor Device ID             Neighbor Port ID           TTL
Et2/1      CN-Arista2                       Ethernet5/1                120
Et2/2      CN-Arista2                       Ethernet5/2                120
Et2/3      CN-Arista3                       Ethernet5/3                120
Et2/4      CN-Arista                       Ethernet5/4                120
Et64/1     CN-Spine2                      Ethernet64/1               120
Ma1        Arista01.Dmech.rack01             Ethernet1                  120
"""


#create a test file
fn_in = "./testin.txt"
fn_out = "./testout.txt"

with open(fn_in, "w") as fo:
    fo.write(input)

with open(fn_in, "r") as fi, open(fn_out,"w") as fo:

    #drop first line
    for line in fi.readlines()[1:]:
        #split without argument treats consecutive spaces as 1 separator
        #drop last field
        fields = line.split()[:-1]
        fo.write(", ".join(fields)+"\n")

did it work?

$ cat testout.txt


Et2/1, CN-Arista2, Ethernet5/1
Et2/2, CN-Arista2, Ethernet5/2
Et2/3, CN-Arista3, Ethernet5/3
Et2/4, CN-Arista, Ethernet5/4
Et64/1, CN-Spine2, Ethernet64/1
Ma1, Arista01.Dmech.rack01, Ethernet1
Comments