python—yaml

一、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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑*杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值