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

后端 未结 1 489
-上瘾入骨i
-上瘾入骨i 2020-11-29 00:30

I am new to YAML and have been searching for ways to parse a YAML file and use/access the data from the parsed YAML.

I have come across explanations on how to parse

相关标签:
1条回答
  • 2020-11-29 01:03

    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 yaml
    with 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.

    0 讨论(0)
提交回复
热议问题