from ruamel.yaml import YAML
yaml=YAML(typ='safe')
yaml.load(doc)
以上typ若没有指定,默认为 'rt' (round-trip);
doc可以是文件指针(即具有.read()方法、字符串或pathlib.Path()的对象);
typ='safe'完成了与safe_load()之前相同的操作:加载文档而不解析未知标记;
pure=True以使用纯Python实现强制执行,否则将在可能/可用时使用更快的C库。
详细的可以参考源码:
classYAML:def__init__(self,*, typ=None, pure=False, output=None, plug_ins=None):# input=None,# type: (Any, Optional[Text], Any, Any, Any) -> None"""
typ: 'rt'/None -> RoundTripLoader/RoundTripDumper, (default)
'safe' -> SafeLoader/SafeDumper,
'unsafe' -> normal/unsafe Loader/Dumper
'base' -> baseloader
pure: if True only use Python modules
input/output: needed to work as context manager
plug_ins: a list of plug-in files
"""
defload(self, stream):# type: (Union[Path, StreamTextType]) -> Any"""
at this point you either have the non-pure Parser (which has its own reader and
scanner) or you have the pure Parser.
If the pure Parser is set, then set the Reader and Scanner, if not already set.
If either the Scanner or Reader are set, you cannot use the non-pure Parser,
so reset it to the pure parser and set the Reader resp. Scanner if necessary
"""ifnothasattr(stream,'read')andhasattr(stream,'open'):# pathlib.Path() instancewith stream.open('rb')as fp:return self.load(fp)
constructor, parser = self.get_constructor_parser(stream)try:return constructor.get_single_data()finally:
parser.dispose()try:
self._reader.reset_reader()except AttributeError:passtry:
self._scanner.reset_scanner()except AttributeError:pass
3.2 yaml.dump()写ymal文件
from ruamel.yaml import YAML
yaml=YAML()
yaml.default_flow_style =False
yaml.dump({'a':[1,2]}, s)