1. Let’s store a few ip addresses in the file as a list.
YAML File: Yaml_file_1.yml
---
# Three hyphens at the top are mandatory and are used to signify the start of a YAML file.
- 1.1.1.1 # The space after the hyphen is mandatory and proper spacing is very important in YAML file.
- 2.2.2.2 # Another thing to notice here is that these ip addss' are being input as strings but I did not have to use any quotes("")
- 192.168.25.11
- 192.168.25.12
Let’s now work with this file in python.
Library to work with yaml in python: pyyaml
It can installed using the command: pip install pyyaml
Python Script: Yaml_read_1.py
import yaml
yaml_file = r'Yaml_file_1.yml'
with open(yaml_file) as f:
output = yaml.safe_load(f)
print(output)
print(type(output))
Output:
['1.1.1.1', '2.2.2.2', '192.168.25.11', '192.168.25.12']
<class 'list'>
We just created a list in yaml.
2. Now, let’s learn how to create a dictionary in yaml.
YAML File: Yaml_file_2.yml
---
rtr1: 1.1.1.1 # We used a ': '(colon + space) in between the key and value pair just like we do in python dictionary.
rtr2: 2.2.2.2
rtr3: 192.168.25.11
Let’s now work with this file in python.
import yaml
yaml_file = r'C:\Users\admin\5_day_program\DAY2\Yaml_file_2.yml'
with open(yaml_file) as f:
output = yaml.safe_load(f)
print(output)
print(type(output))
# For Dictionary
print(output['rtr1'])
print(output['rtr2'])
Output:
{'rtr1': '1.1.1.1', 'rtr2': '2.2.2.2', 'rtr3': '192.168.25.11'} # We see that the key and values are of string type and we did not have to use any kind of quotes in the YAML file to acheive that.
<class 'dict'>
1.1.1.1
2.2.2.2 