Skip to content Skip to sidebar Skip to footer

Python To Handle Text File To Print Its Output

I am very new to python and I need to read below file (Actually below output get it from command ) and print its output. Below is the file: NIC: Name: eth0 ID: 0 1 Dynamic

Solution 1:

the text looks la YAML, but it's not, but it could be

with open("vnic1.txt") as f:
   data = f.read()
# makeing it yaml-string
data = dat.replace("  Name","- Name") # the 2 spaces are intended
import yaml
data = yaml.load(data) # you now have the entire structure as a huge dict, profit

this way you'll have in data something like this

{
    'NIC': [
        {'Dynamic MAC Addr': '00:00:00:00:00:01',
         'Ethernet Interface': [{'Config Qual': 'N/A',
                                 'Default Network': True,
                                 'Name': 'prod',
                                 'Operational VLAN': 'SWA',
                                 'VLAN ID': 2},
                                {'Config Qual': 'N/A',
                                 'Default Network': False,
                                 'Name': 'dev',
                                 'Operational VLAN': 'SWA',
                                 'VLAN ID': 3}],
         'ID': '0 1',
         'Name': 'eth0',
         'Preference': 'NONE'},
        {'Dynamic MAC Addr': '00:00:00:00:00:11',
         'Ethernet Interface': [{'Config Qual': 'N/A',
                                 'Default Network': True,
                                 'Name': 'prod',
                                 'Operational VLAN': 'SWB',
                                 'VLAN ID': 2},
                                {'Config Qual': 'N/A',
                                 'Default Network': False,
                                 'Name': 'dev',
                                 'Operational VLAN': 'SWB',
                                 'VLAN ID': 3}],
         'Fabric ID': '1 0',
         'Name': 'eth1',
         'Preference': 'NONE'}
    ]
}

which might not be what you asked for, but will definitely be a lot more easy to navigate (at least you have the sections correctly separated)


Post a Comment for "Python To Handle Text File To Print Its Output"