How can I parse a YAML file in Python

后端 未结 8 1231
醉话见心
醉话见心 2020-11-22 14:54

How can I parse a YAML file in Python?

8条回答
  •  醉话见心
    2020-11-22 15:29

    If you have YAML that conforms to the YAML 1.2 specification (released 2009) then you should use ruamel.yaml (disclaimer: I am the author of that package). It is essentially a superset of PyYAML, which supports most of YAML 1.1 (from 2005).

    If you want to be able to preserve your comments when round-tripping, you certainly should use ruamel.yaml.

    Upgrading @Jon's example is easy:

    import ruamel.yaml as yaml
    
    with open("example.yaml") as stream:
        try:
            print(yaml.safe_load(stream))
        except yaml.YAMLError as exc:
            print(exc)
    

    Use safe_load() unless you really have full control over the input, need it (seldom the case) and know what you are doing.

    If you are using pathlib Path for manipulating files, you are better of using the new API ruamel.yaml provides:

    from ruamel.yaml import YAML
    from pathlib import Path
    
    path = Path('example.yaml')
    yaml = YAML(typ='safe')
    data = yaml.load(path)
    

提交回复
热议问题