sunita
sunita

Reputation: 13

Load a yaml file and Iterate over a list in python

I have a yaml file with the below content:

testcases:
 - testcase_1:
    username:
    password:
 - testcase_2:
    username:
    password:  

How do I iterate through the over content. I want first to run testcases with the variables present inside testcases_1 and then later run testcases with variables in testcase_2. ? How do I do this ?///

Upvotes: 0

Views: 6889

Answers (1)

Dan Constantinescu
Dan Constantinescu

Reputation: 1526

You can use yaml.safe_load function to load the content and then you can iterate over it:

import yaml

content = None

with open("D:/data.yml") as f:
    try:
        content = yaml.safe_load(f)
    except yaml.YAMLError as e:
        print(e)

print(content)

for item in content['testcases']:
    print(item)

Above code will output:

{'testcases': [{'testcase_1': {'username': None, 'password': None}}, {'testcase_2': {'username': None, 'password': None}}]}
{'testcase_1': {'username': None, 'password': None}}
{'testcase_2': {'username': None, 'password': None}}

Upvotes: 4

Related Questions