python模块02 - 使用python读取yaml

Yaml 

        yaml是一种可读性高,用来表达资料序列化的格式

1.1 yaml提供格式

从python角度来看,yaml提供以下格式

  • Dict

Dict 是最基本的格式,任何有“:” 的地方都以 Dict 来呈现

resources:
 cpu: .5
 memory_gb: 1
 disk_size_gb: 10

Parse后:

‘resources’: {‘disk_size_gb’: 10, ‘cpu’: 0.5, ‘memory_gb’: 1}
  • List: 

通过每个选项前面加 ‘-’ 实现

skip_files:
 — ^(.*/)?#.*#$
 — ^(.*/)?.*~$
 — ^(.*/)?.*\.py[co]$
 — ^(.*/)?.*/RCS/.*$
 — ^(.*/)?\..*$

Parse后:

'skip_files': [‘^(.*/)?#.*#$’, ‘^(.*/)?.*~$’, ‘^(.*/)?.*\\.py[co]$’, ‘^(.*/)?.*/RCS/.*$’, ‘^(.*/)?\\..*$’, ‘bin/’, ‘__pycache__/’, ‘lib/’, ‘include/’, ‘pip-selfcheck.json’]
  • 存储分行文字

test_block: |
 first line
 second line

Parse后,每个分行后面加上\n

‘test_block’: ‘first line\nsecond line\n’
  • 另外一种分行字符 >

test_block1: >
 first line
 second line

Parse后,会变为同一行以空格间隔

'test_block1': ‘first line second line\n’

1.2 python读取yaml

a) 安装模块

安装 pyyaml: pip install pyyaml

 

b) 编写yaml文件

log:
  name: "python"
  file: "python.txt"
  logger_level: "DEBUG"
  stream_level: "DEBUG"
  file_level: "INFO"

excel:
  file: "cases.xlsx"

people:
  - xiaoyi
  - xiaoer

demo:
  age: 16

c) 文件读取:yaml.load

一个yaml文件加载出来为一个字典对象,读取出来是字典

import yaml

with open("config.yaml", 'r', encoding='utf-8') as f:
    data = yaml.load(f, Loader = yaml.FullLoader)
    print(data)


"""结果
{'log': {'name': 'python', 'file': 'python.txt', 'logger_level': 'DEBUG', 'stream_level': 'DEBUG', 'file_level': 'INFO'},
 'excel': {'file': 'cases.xlsx'}, 
'people': ['xiaoyi', 'xiaoer'], 
'demo': {'age': 16}}


"""

d) 文件写入:yaml.dump

#写入
with open("anthon.yaml", "w",encoding="utf8") as f:
    yaml.dump({"log": "logdemo"}, f)

1.3 封装

import yaml

def read_yaml(file):
    "读取yaml文件"
    with open(file, encoding='utf8') as f:
        conf = yaml.load(f, Loader=yaml.FullLoader)
    return conf


def write_yaml(file, data):
    with open(file, "w", encoding="utf8") as f:
        yaml.dump({data}, f)

1.4 注意事项,易导致报错点

注意1:yaml文件编写一定要加空格否则不会高亮显示,会报错

  pprint(yaml_data["excel"]["file"])
TypeError: string indices must be integers

修改后: 

欢迎补充@~@

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值