14.19. python读写yaml

14.19.1. 1.安装PyYAML

使用以下命令安装 PyYAML,最好在虚拟环境中

虚拟环境安装参考: https://python.land/virtual-environments/virtualenv

$ pip install pyyaml

On some systems you need to use pip3:

$ pip3 install pyyaml

To use PyYAML in your scripts, import the module as follows. Note that you don’t import ‘pyyaml’, but simply ‘yaml’:

import yaml

14.19.2. 2.使用Python读取和解析YAML文件

config.yaml

rest:
  url: "https://example.org/primenumbers/v1"
  port: 8443
prime_numbers: [2, 3, 5, 7, 11, 13, 17, 19]

parsing_yaml.py

import yaml

with open("config.yaml","r") as file:
    prime_service = yaml.safe_load(file)


print(prime_service)
# {'rest': {'url': 'https://example.org/primenumbers/v1', 'port': 8443}, 'prime_numbers': [2, 3, 5, 7, 11, 13, 17, 19]}
print(prime_service['prime_numbers'][0])    # 2

print(prime_service["rest"]["url"])
# https://example.org/primenumbers/v1

14.19.3. 3.使用Python解析YAML字符串

您可以使用 yaml.safe_load()来解析各种有效的YAML字符串。这是一个将简单的项目列表解析为 Python列表的示例:

import yaml

names_yaml = """
    - 'eric'
    - 'justin'
    - 'mary-kate'
"""
names = yaml.safe_load(names_yaml)

print(names)
# ['eric', 'justin', 'mary-kate']

14.19.4. 4.解析包含多个YAML文档的文件

YAML允许您在一个文件中定义多个文档,并用三个破折号 (—) 分隔它们。

PyYAML 也会愉快地解析这些文件,并返回一个文档列表。您可以使用 yaml.safe_load_all()函数来执行此操作。

此函数返回一个生成器,该生成器又将一个接一个地返回所有文档。

multi_doc.yml

document: 1
name: 'erik'
---
document: 2
name: 'config'

read_multiple_yaml.py

import yaml

with open('multi_doc.yml', 'r') as file:
    docs = yaml.safe_load_all(file)

    for doc in docs:
        print(doc)

14.19.5. 5.将YAML写入转储到文件

import yaml

names_yaml = """
- 'eric'
- 'justin'
- 'mary-kate'
"""

names = yaml.safe_load(names_yaml)

with open('names.yaml', 'w') as file:
    yaml.dump(names, file)

14.19.6. 6.使用Python将YAML转换为JSON

在这个例子中,我们打开一个基于 YAML 的配置文件,用 PyYAML 解析它,然后用 JSON 模块将它写入一个 JSON 文件

config.yml

rest:
  url: "https://example.org/primenumbers/v1"
  port: 8443

prime_numbers: [2, 3, 5, 7, 11, 13, 17, 19]

yaml-to-json.py

import yaml
import json

with open('config.yml', 'r') as file:
    configuration = yaml.safe_load(file)

with open('config.json', 'w') as json_file:
    json.dump(configuration, json_file)

output = json.dumps(json.load(open('config.json')), indent=2)
print(output)

这是与非交互式示例相同的代码

import yaml
import json
with open('config.yml', 'r') as file:
    configuration = yaml.safe_load(file)
with open('config.json', 'w') as json_file:
    json.dump(configuration, json_file)

14.19.7. 7.将JSON转换为YAML

为了完整起见,我们也反过来:将JSON转换为YAML

config.json

{
  "rest": {
    "url": "https://example.org/primenumbers/v1",
    "port": 8443
  },
  "prime_numbers": [
    2,
    3,
    5,
    7,
    11,
    13,
  ]
}

json-to-yaml.py

import yaml
import json

with open('config.json', 'r') as file:
    configuration = json.load(file)

with open('config.yaml', 'w') as yaml_file:
    yaml.dump(configuration, yaml_file)

with open('config.yaml', 'r') as yaml_file:
    print(yaml_file.read())

14.19.8. 8.参考文献

https://pyyaml.org/wiki/PyYAMLDocumentation

https://python.land/data-processing/python-yaml