Parsing a YAML file in Python, and accessing the data? Parsing a YAML file in Python, and accessing the data? python python

Parsing a YAML file in Python, and accessing the data?


Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yamlwith open('tree.yaml', 'r') as f:    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]print txt"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.


Just an FYI on @Aphex's solution -

In case you run into -

"YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated"

you may want to use the Loader=yaml.FullLoader or Loader=yaml.SafeLoader option.

import yaml with open('cc_config.yml', 'r') as f:    doc = yaml.load(f, Loader=yaml.FullLoader) # also, yaml.SafeLoadertxt = doc["treeroot"]["branch1"]print (txt)