python之读写yaml

第三方包pyyaml

安装:pip install pyyaml

一组数据读写

  • 读取一组数据:yaml.load()
  • 写一组数据:yaml.dump()
    import yaml
    import os
    
    
    current_path = os.getcwd() # 获取当前工作目录
    path = os.path.join(current_path, 'b.yaml')  #路径拼接
    
    aproject = {'name': 'yaya',
                'race': '花花',
                'traits': ['ONE_HAND', 'ONE_EYE']
                }
    
    # 写入yaml
    with open(path, 'w', encoding='utf-8')as f1:
        # 字符串写入yaml中
        yaml.dump(aproject, f1, default_flow_style=False, encoding='utf-8', allow_unicode=True)
    
    # 读
    with open(path, 'r', encoding='utf-8')as f2:
        # 读取,此时读取出来的是字符串
        data = f2.read()
        # 将读取的内容转化成字典
        # 添加Loader=yaml.FullLoader,不然会有warning
        result = yaml.load(data, Loader=yaml.FullLoader)
        print(result)

    多组数据读写

  • 读取多组数据:yaml.load_all()
    返回结果为一个生成器,需要使用for循环语句获取每组数据
  • 写多组数据:yaml.dump_all()
    import yaml
    import os
    
    current_path = os.getcwd()  # 获取当前工作目录
    path = os.path.join(current_path, 'b.yaml')
    
    user1 = {
        'name': '丽丽',
        'age': 18,
        'like': {'kecheng': '语文','yundong': '跑步'}
    }
    
    user2 = {
        'name': '花花',
        'age': 17,
        'like': {'kecheng': '数学','yundong': '跳高'}
    }
    
    # 写
    with open(path, 'w', encoding='utf-8')as f1:
        # 字符串写入yaml中
        yaml.dump_all([user1, user2], f1, default_flow_style=False, encoding='utf-8', allow_unicode=True)
    
    # 读
    with open(path, 'r', encoding='utf-8')as f2:
        data = f2.read()
        # 添加Loader=yaml.FullLoader,不然会有warning
        result = yaml.load_all(data, Loader=yaml.FullLoader)
        for i in result:
            print(i)

     

posted @ 2022-07-24 16:19  yaya_zhang  阅读(552)  评论(0编辑  收藏  举报