> pip install pyyaml
pyyaml 是第三方库,需要导入
扩展:Python 安装第三方库详解:https://blog.csdn.net/qq_34745941/article/details/106341898
# 格式1: 单个字典
key: value
# 格式2:多维字典
key:
child-key: value
child-key2: value2
database:
host: localhost
port: 1521
username: user
passwoed: 123
输出测试:(以多维字典为例)
import yaml
fileName = 'Demo.yaml'
# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:
config = yaml.load(file, Loader=yaml.FullLoader)
print(config)
print(config['database']['username'])
输出结果:
{'database': {'host': 'localhost', 'port': 1521, 'username': 'user', 'passwoed': 123}}
user
# 格式1:单个数组
- A
- B
- C
# 格式2: 多维数组
-
- key1
- key2
-
- value1
- value2
输出测试:(以多维数组为例)
import yaml
fileName = 'Demo.yaml'
# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:
config = yaml.load(file, Loader=yaml.FullLoader)
print(config)
print(config[0])
输出结果:
[['key1', 'key2'], ['value1', 'value2']]
['key1', 'key2']
langusges:
- Java
- Python
- Sql
person:
name: 张三
age: 18
输出测试:
import yaml
fileName = 'Demo.yaml'
# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:
config = yaml.load(file, Loader=yaml.FullLoader)
print(config)
输出结果:
{'langusges': ['Java', 'Python', 'Sql'], 'person': {'name': '张三', 'age': 18}}
import yaml
fileName = 'Demo.yaml'
# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:
config = yaml.load(file, Loader=yaml.FullLoader)
print(config)
import yaml
fileName = 'Demo.yaml'
users = [{'name': '张三', 'age': 18},
{'name': '李四', 'age': 19}]
with open(fileName, mode='w', encoding='UTF-8') as file:
yaml.dump(users, file, sort_keys=False, allow_unicode=True)
输出结果:
- name: 张三
age: 18
- name: 李四
age: 19