python yaml用法详解

时间:2023-01-15 07:49:11

YAML是一种直观的能够被电脑识别的的数据序列化格式,容易被人类阅读,并且容易和脚本语言交互。YAML类似于XML,但是语法比XML简单得多,对于转化成数组或可以hash的数据时是很简单有效的。 
PyYaml 

  • 1、load() :返回一个对象 
    我们先创建一个yml文件,config.yml:
    name: Tom Smith
    age: 37
    spouse:
        name: Jane Smith
        age: 25
    children:
     - name: Jimmy Smith
       age: 15
     - name1: Jenny Smith
       age1: 12
  • 读取yml文件:
    import yaml
    f = open(r'E:\AutomaticTest\Test_Framework\config\config.yml')  #  传入文件路径
    y = yaml.load(f)
    print (y)
    结果:
    {'name': 'Tom Smith', 'age': 37, 'spouse': {'name': 'Jane Smith', 'age': 25}, 'children': [{'name': 'Jimmy Smith', 'age': 15}, {'name1': 'Jenny Smith', 'age1': 12}]}

    2、load_all()生成一个迭代器 
    如果string或文件包含几块yaml文档,你可以使用yaml.load_all来解析全部的文档

    import yaml
    f = '''
    ---
    name: James
    age: 20
    ---
    name: Lily
    age: 19
    '''
    y = yaml.load_all(f)
    for data in y:
        print(data)
    执行结果:
    {'name': 'James', 'age': 20}
    {'name': 'Lily', 'age': 19}

    3、yaml.dump 将一个python对象生成为yaml文档

    import yaml
    aproject = {'name': 'Silenthand Olleander',
                'race': 'Human',
                'traits': ['ONE_HAND', 'ONE_EYE']
                }
    
    print(yaml.dump(aproject,))
    执行结果:
    name: Silenthand Olleander
    race: Human
    traits: [ONE_HAND, ONE_EYE]
  • yaml.dump接收的第二个参数一定要是一个打开的文本文件或二进制文件,yaml.dump会把生成的yaml文档写到文件里
    import yaml
    
    aproject = {'name': 'Silenthand Olleander',
                'race': 'Human',
                'traits': ['ONE_HAND', 'ONE_EYE']
                }
    f = open(r'E:\AutomaticTest\Test_Framework\config\config.yml','w')
    yaml.dump(aproject,f)
    print(yaml.load( open(r'E:\AutomaticTest\Test_Framework\config\config.yml')))
    执行结果:
    {'name': 'Silenthand Olleander', 'race': 'Human', 'traits': ['ONE_HAND', 'ONE_EYE']}

    4、yaml.dump_all()将多个段输出到一个文件中

    import yaml
    
    obj1 = {"name": "James", "age": 20}
    obj2 = ["Lily", 19]
    
    with open(r'E:\AutomaticTest\Test_Framework\config\config.yml', 'w') as f:
        yaml.dump_all([obj1, obj2], f)
    输出到文件:
    {age: 20, name: James}
    --- [Lily, 19]

     5、构造器(constructors)、表示器(representers)、解析器(resolvers ) 

  • yaml.YAMLObject 
    yaml.YAMLObject用元类来注册一个构造器(也就是代码里的 init() 方法),让你把yaml节点转为Python对象实例,用表示器(也就是代码里的 repr() 函数)来让你把Python对象转为yaml节点,看代码:
    import yaml
    class Person(yaml.YAMLObject):
        yaml_tag = '!person'
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __repr__(self):
            return '%s(name=%s, age=%d)' % (self.__class__.__name__, self.name, self.age)
    
    james = Person('James', 20)
    
    print (yaml.dump(james))  # Python对象实例转为yaml
    
    lily = yaml.load('!person {name: Lily, age: 19}')
    
    print (lily)  # yaml转为Python对象实例
    输出:
    !person {age: 20, name: James}
    
    Person(name=Lily, age=19)
  • yaml.add_constructor 和 yaml.add_representer 
    你可能在使用过程中并不想通过上面这种元类的方式,而是想定义正常的类,那么,可以用这两种方法

    import yaml
    
    
    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __repr__(self):
            return 'Person(%s, %s)' % (self.name, self.age)
    
    james = Person('James', 20)
    print (yaml.dump(james))  # 没加表示器之前
    
    
    def person_repr(dumper, data):
        return dumper.represent_mapping(u'!person', {"name": data.name, "age": data.age})  # mapping表示器,用于dict
    
    yaml.add_representer(Person, person_repr)  # 用add_representer方法为对象添加表示器
    print (yaml.dump(james))  # 加了表示器之后
    
    
    def person_cons(loader, node):
        value = loader.construct_mapping(node)  # mapping构造器,用于dict
        name = value['name']
        age = value['age']
        return Person(name, age)
    
    yaml.add_constructor(u'!person', person_cons)  # 用add_constructor方法为指定yaml标签添加构造器
    lily = yaml.load('!person {name: Lily, age: 19}')
    print (lily)
    !!python/object:__main__.Person {age: 20, name: James}
    !person {age: 20, name: James}
    Person(Lily, 19)

    下面添加了构造器,能够把 !person 标签转化为Person对象

 

原文地址:https://www.cnblogs.com/klb561/p/9326677.html