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
修改后:
欢迎补充@~@