I have been looking into Ansible for automation which has meant looking at YAML files again. I’ve looked at YAML before which in theory offers benefits over ini, JSON and XML based files but the lack of built in module has resulted in me using choosing ini or JSON formats. I have recently been favouring JSON in projects and as this is a subset of YAML it is time to take another look at format.
For a long time the defacto standard library has been PyYAML. There are a bunch of Windows installers on the page which can be used to get up and running. However this module has received few updates in recent years and doesn’t appear to support the later YAML 1.2 standard. Up has stepped Anthon van der Neut who has used this as the basis for his own ruamel.yaml module. This can be installed using pip in the usual way.
Whichever one you choose, you can use safe_load to load a YAML file (or convert a string) and dump to create a YAML string
try: import ruamel.yaml as yaml except ImportError: import yaml pydic = yaml.safe_load(""" # example yaml (this is a comment) name: test version: 1.0 inlinelist: [ "tinker", "tailor", "soldier", "spy" ] yamllist: - first item - second item dictionary: name: subdictionary usage: anything """) print(pydic) with open('test.yml','w') as ymlfile: ymlfile.writelines(yaml.dump(pydic))
There is a limit on what how readable the output from the dump method is as you will see from the above example. If you are using YAML files for configuration you can be much more verbose and use whitespace. There is a full reference card of the YAML 1.1 spec in a single page on the yaml.org website.