testyaml.yaml 文件:
-
user_msg:
name: '黎明'
age: '19'
-
companies:
-
id: 1
name: company1
price: 200W
-
id: 2
name: company2
price: 500W
.py 文件:(要安装 pyyaml,pip install pyyaml)
# coding:utf-8
# yaml文件读取演示案例
import os
import yaml
def read_yaml(path):
with open(path, 'r') as file:
val = file.read()
res = yaml.safe_load(val)
print(res)
if __name__ == '__main__':
curr_path = os.getcwd()
curr_file = 'testyaml.yaml'
path = os.path.join(curr_path, curr_file)
if os.path.exists(path):
read_yaml(path)
# [
# {
# 'user_msg': {'name': '榛庢槑', 'age': '19'}
# },
# {
# 'companies':
# [
# {'id': 1, 'name': 'company1', 'price': '200W'},
# {'id': 2, 'name': 'company2', 'price': '500W'}
# ]
# }
# ]