How to create and read yaml files in python?

0

I understand that in python to be more ordered, .yaml files are used. The problem is that I do not know how to read or create them. Can someone help me?

    
asked by ElAlien123 31.03.2018 в 04:39
source

1 answer

0

You have two different libraries that allow you to interact with the YAML format: pyYAML and ruamel.yaml which is a fork of the previous one.

I have tried both and in my experience ruamel.yaml is more complete and above all faster when it comes to "digest" big yaml files. However it can be more difficult to install because it is not written in pure python (it has C parts).

In any case, regardless of which modules you use to generate or read it, a general comment about YAML. It is a data format equivalent in capacity to JSON. That is, it allows you to store in a file and in an easy-to-read format for people, data that will basically be of the dictionary type (whose keys can only be strings) or lists. The dictionary or list values can be numeric, Boolean, string, or another dictionary or list.

The difference with JSON is the syntax, easier to write "by hand" in an editor by making unnecessary the quotation marks around the strings, commas separating values in a list or dictionary, and braces or brackets to delimit where start and end each list or dictionary. Instead, it will use carriage returns as separators and indentation as a syntactic marker.

So, for example, the following JSON:

{ "configuracion": {
      "IPs": [ "127.0.0.1",
               "192.168.0.1"
             ],
      "puerto": 8000,
      "nombre": "miservidor.com"
   }
}

It would be written like this in YAML:

configuracion:
  IPs:
  - 127.0.0.1
  - 192.168.0.1
  puerto: 8000
  nombre: miservidor.com

Which is (probably) easier to read and especially to write. Although YAML has its complication if we want the value to be a chain that occupies several lines. You can do it, but the syntax becomes more cumbersome.

After reading the previous file with a YAML parser (either of the two I indicated before), what you would have would be a "normal" python dictionary, let's call it d , from which you can access, for example, the port , with d["configuracion"]["puerto"] , or the first IP with d["configuracion"]["IPs"][0] , etc.

Consider whether it will be worthwhile to use the JSON version directly instead of the YAML. If your configuration file is not very complex, the JSON syntax is not so cumbersome and the advantage is that the parser json already comes with python and you do not have to install anything extra.

    
answered by 31.03.2018 в 13:10