栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python字典与yaml文件转换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python字典与yaml文件转换

使用pyyaml库对dict类型数据与yaml格式文件做转换,首先安装:

pip install pyyaml
示例代码
import yaml


def save_dict_to_yaml(dict_value: dict, save_path: str):
    """dict保存为yaml"""
    with open(save_path, 'w') as file:
        file.write(yaml.dump(dict_value, allow_unicode=True))


def read_yaml_to_dict(yaml_path: str, ):
    with open(yaml_path) as file:
        dict_value = yaml.load(file.read(), Loader=yaml.FullLoader)
        return dict_value


if __name__ == '__main__':
    my_config_dict = {
        "mysql": {
            "host": "127.0.0.1",
            "tables": ["table_1", "table_2"],
        },
        "redis": {
            "host": "127.0.0.1",
            "db": 3,
        }
    }
    # 保存yaml
    save_dict_to_yaml(my_config_dict, "config.yaml")
    # 读取yaml
    config_value = read_yaml_to_dict("config.yaml")
    assert config_value == my_config_dict

使用示例也可参考:python读取yaml文件

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/740451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号