This post will discuss how to parse a YAML file in Python.

1. Using yaml.load() function

The PyYAML module is a recommended YAML parser and emitter for Python. To convert a YAML file to a Python object, you can use the yaml.load() function.

If your YAML data is coming from trusted sources, you can specify the Loader=FullLoader argument, which loads the full YAML language and avoid arbitrary code execution.

Download Code

 
This is equivalent to calling the yaml.full_load() function.

Download Code

2. Using yaml.safe_load() function

You can use the yaml.load() function to load the untrusted data, but only with yaml.SafeLoader Loader.

Download Code

 
Alternatively, PyYAML provides a safe_load() function that can be used to load data by an untrusted source.

Download Code

That’s all about parsing a YAML file in Python.