Max Max - 25 days ago 24
YAML Question

read and sort line block of yaml file in python

I am trying to sort a yaml file with python which looks like this:

........
........
........
# comment
ip address/20:
datacenter: x
context: y
# comment
ip address/32:
datacenter: a
context: b
# comment
ip address/24:
datacenter: x
context: z
# comment
ip address/16:
datacenter: a
context: b
........
........
........


the file is very long. I could achieve reading the file with python, but I would like to sort the out put blocks depending on CIDR notation:

........
........
........
# comment
ip address/16:
datacenter: a
context: b
# comment
ip address/20:
datacenter: x
context: y
# comment
ip address/24:
datacenter: x
context: z
# comment
ip address/32:
datacenter: a
context: b
........
........
........


Is there any way to do it while reading the file:

import yaml

with open("file.yml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as err:
print(err)


or should I read the file line by line? Thanks a lot.

Max Max
Answer

I had some time to work on it, and I came up with the following solution:

#!/usr/bin/env python3

 import yaml
 #from functools import reduce

with open("sprd_variator.yml", 'r') as input_file:
    try:
        dict = yaml.load(input_file)
        i = 'networks'
        if i in dict:
            sorted_sub = sorted(dict[i].items())
            sorted_sub_keys = sorted(dict[i].keys())
            sorted_sub_keys.sort(key = lambda x: int(x.rsplit('/',2)[1]))
            networks = []
            for x in sorted_sub_keys:
                facters = [item for item in sorted_sub if item[0] == x]
                networks.append(facters)
                one_list = [item for sublist in networks for item in sublist]
                #one_list = reduce(lambda x,y: x+y,networks)
            print(one_list)
        else:
            print('error')
    except yaml.YAMLError as err:
        print(err)

Thanks a lot.

Comments