How to Get & Parse Data From a YAML File in Python
To get data from a YAML file in Python, import the PyYAML Python package then use the yaml.load()
function to parse a file object as a dictionary.
To demonstrate this, let's open a .yaml
file with the Python open()
function and parse the data with PyYAML.
Homestead.yaml
---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
- ~/.ssh/id_rsa
folders:
- map: ~/code
to: /home/vagrant/code
sites:
- map: homestead.test
to: /home/vagrant/code/public
databases:
- homestead
features:
- mariadb: false
- ohmyzsh: false
- webdriver: false
# ports:
# - send: 50000
# to: 5000
# - send: 7777
# to: 777
# protocol: udp
import yaml
yaml_file = open('Homestead.yaml')
parsed = yaml.load(yaml_file, Loader=yaml.FullLoader)
print(parsed)
{'ip': '192.168.10.10', 'memory': 2048, 'cpus': 2, 'provider': 'virtualbox', 'authorize': '~/.ssh/id_rsa.pub', 'keys': ['~/.ssh/id_rsa'], 'folders': [{'map': '~/code', 'to': '/home/vagrant/code'}], 'sites': [{'map': 'homestead.test', 'to': '/home/vagrant/code/public'}], 'databases': ['homestead'], 'features': [{'mariadb': False}, {'ohmyzsh': False}, {'webdriver': False}]}
The second argument passed in the yaml.load()
function is the loader to use – this argument is required for newer versions of PyYAML or an error will be thrown. Typically for parsing files, the value of Loader
will be yaml.FullLoader
.
yaml
file