python—yaml

python—yaml,第1张

一、Yaml的基本语法基本语法
  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #标识注释,从这个字符一直到行尾,都会被解释器忽略
二、读字典
yaml文件内容:
name: Steve
age: 18
hash: 
  name: Steve,
  age: 18


import yaml
with open('./yamldata.yaml', 'r', encoding='utf-8') as r:
    '''
    windows环境下,读取yaml文件时不能出现中文,包括注释;
    默认是使用gbk,所以这里需要定义一下utf-8 
    '''
    a=yaml.safe_load(r)
    print(a)

返回结果:
{'name': 'Steve', 'age': 18, 'hash': {'name': 'Steve', 'age': 18}}
三、读列表
yaml文件内容:
- animal
- a
- b

返回结果:
['animal', 'a', 'b']
四、复合结构
self-check:
  functionSwitch: true
  cityList:
    - city: 440300
      sources: 2
  allSourceConfigList:
    - source: 1
      title: 请拍摄驾驶
    - source: 2
      title: 请拍摄车身
    - source: 3
      title: 请拍摄车身右侧

返回结果:
{'self-check': {'functionSwitch': True, 'cityList': [{'city': 440300, 'sources': 2}], 'allSourceConfigList': [{'source': 1, 'title': '请拍摄驾驶'}, {'source': 2, 'title': '请拍摄车身'}, {'source': 3, 'title': '请拍摄车身右侧'}]}}

五、写文件
import yaml

file = "a.yaml"
with open(file, "w", encoding='utf-8') as f:
    data = {
        "name": "aaa",
        "age": 25,
        "hobby": ["Singing", "dancing", "rap", "basketball"],
        "game": {
            "ps5": ["幻想", "地平线"],
            "switch": ["森林", "传说"],
        }
    }

    # allow_unicode=True,解决存储时unicode编码问题。
    # sort_keys=False,解决写入yaml的数据则不会排序后写入。
    f.write(yaml.dump(data, allow_unicode=True, sort_keys=False))

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/919004.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存