yaml 示例
- - 开头表示列表, 可以不缩进
- k: v 表示字典格式
- None 用 ~ 表示
# json 示例: [
# {"name": "Tim, "age": 18, "score": {"chinese": 99, "math": 100}, "hobby": ["lol", "wow"]},
# {"name": "Tom, "age": 18, "score": {"chinese": None, "math": 100}, "hobby": ["lol", "wow"]},
# ]
- name: Tim
age: 18
score:
chinese: 99
math: 100
hobby:
- lol
wow
- name: Tom
age: 20
score:
chinese: ~
math: 100
hobby:
- lol
wow
解析示例
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import yaml
def main():
# 我的目录结构是 projectPath/bin/main.py, projectPath/conf/xx.yml
with open(os.path.join(sys.path[-1], "conf", "xx.yml"), "r") as f:
r = yaml.load(f, Loader=yaml.FullLoader)
# 此时 r 已经从 yaml 格式转为了 list or dict 格式了
print(type(r))
print(r)
if __name__ == '__main__':
main()