zoukankan      html  css  js  c++  java
  • Python读取YAML文件

    YAML语法 学习手册

    Python读取方法:

    import yaml
    
    with open('demo1.yaml', 'r', encoding='utf-8') as f:
        file_content = f.read()
    
    content = yaml.load(file_content, yaml.FullLoader)
    print(content)
    

    demo1.yaml

    - 123                         # int
    - 3.14                        # float
    - true                        # bool,不区分大小写
    - False                       # bool
    - string                      # 字符串
    - ''                          # 空字符串
    - ~                           # ~代表 null,Python中的 None
    -                             # 同上
    - 2019-12-12                  # date
    - 2019-12-12T14:59:59+08:00   # datetime
    - name: Miles                 # dict
      age: 22
    

    使用以上方法后的结果是一个列表,手动换行了方便阅读:

    [
     123,
     3.14,
     True,
     False,
     'string',
     '',
     None,
     None,
     datetime.date(2019, 12, 12),
     datetime.datetime(2019, 12, 12, 6, 59, 59),
     {'name': 'Miles', 'age': 22}
    ]
    

    demo2.yaml

    name: Miles
    age: 18
    single: true
    dream: ~
    lucky number:
      - 8
      - 9
      - 12
    

    这种形式经过方法读取是一个字典:

    {
     'name': 'Miles',
     'age': 18,
     'single': True,
     'dream': None,
     'lucky number':[8, 9, 12]
    }
    
  • 相关阅读:
    前端之JavaScript内容
    前端之CSS内容
    前端之HTML内容
    表单提交中的input、button、submit的区别
    PostgreSQL
    PostgreSQL
    PostgreSQL
    JIRA中的标记语言的语法参考
    Markdown
    Linux
  • 原文地址:https://www.cnblogs.com/milesma/p/12112087.html
Copyright © 2011-2022 走看看