编程语言
首页 > 编程语言> > Python 常用第三方库 yaml

Python 常用第三方库 yaml

作者:互联网

YAML

YAML 基本语法规则

YAML 支持的数据结构

# 编程语言
languages:
  - PHP
  - Java
  - Python 
book:
  Python入门: # 书籍名称
    price: 55.5
    author: Lily
    available: True
    repertory: 20
    date: 2018-02-17
  Java入门:
    price: 60
    author: Lily
    available: False
    repertory: Null
    date: 2018-05-11

PyYAML

  • Python 的 YAML 解析器和生成器
  • 官网:https://pypi.org/project/PyYAML/

安装:pip install pyyaml

创建 yaml 文件

import yaml

data = {
    "client": {"default-character-set": "utf8"},
    "mysql": {"user": 'root', "password": 123},
    "custom": {
        "user1": {"user": "张三", "pwd": 666},
        "user2": {"user": "李四", "pwd": 999},
    }
}
# 直接 dump 可以把对象转为 YAML 文档
with open('./my.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(data, f, allow_unicode=True)

读取 yaml 文件

import yaml

file_path = './my.yaml'

with open(file_path, 'r', encoding='utf-8') as f:
    data = yaml.safe_load(f)
print(data)

标签:缩进,YAML,Python,yaml,user,data,第三方
来源: https://www.cnblogs.com/manshuoli/p/16224751.html