def load(stream, Loader=None):
Parse the first YAML document in a stream
and produce the corresponding Python object.
if Loader is None:
load_warning('load')
Loader = FullLoader
loader = Loader(stream)
return loader.get_single_data()
finally:
loader.dispose()
def dump(data, stream=None, Dumper=Dumper, **kwds):
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
return dump_all([data], stream, Dumper=Dumper, **kwds)
load:
将yaml流转化为python字典;
dump:
将python对象转化为yaml流;
03 读写yaml配置文件
将读写yaml配置文件的类进行封装。
在common目录下新建一个文件,config_handler.py用于读写yaml。
config_handler.py
import yaml
class YamlHandler:
def __init__(self,file):
self.file = file
def read_yaml(self,encoding='utf-8'):
"""读取yaml数据"""
with open(self.file, encoding=encoding) as f:
return yaml.load(f.read(), Loader=yaml.FullLoader)
def write_yaml(self, data, encoding='utf-8'):
"""向yaml文件写入数据"""
with open(self.file, encoding=encoding, mode='w') as f:
return yaml.dump(data, stream=f, allow_unicode=True)
if __name__ == '__main__':
data = {
"user":{
"username": "vivi",
"password": "123456"
# 读取config.yaml配置文件数据