Parse a YAML file in Python
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.
|
1 2 3 4 5 6 7 8 9 |
import yaml with open('config.yaml') as f: try: dict = yaml.load(f, Loader=yaml.FullLoader) print(dict) except yaml.YAMLError as e: print(e) |
This is equivalent to calling the yaml.full_load() function.
|
1 2 3 4 5 6 7 8 9 |
import yaml with open('config.yaml') as f: try: dict = yaml.full_load(f) print(dict) except yaml.YAMLError as e: print(e) |
2. Using yaml.safe_load() function
You can use the yaml.load() function to load the untrusted data, but only with yaml.SafeLoader Loader.
|
1 2 3 4 5 6 7 8 9 |
import yaml with open('config.yaml') as f: try: dict = yaml.load(f, Loader=yaml.SafeLoader) print(dict) except yaml.YAMLError as e: print(e) |
Alternatively, PyYAML provides a safe_load() function that can be used to load data by an untrusted source.
|
1 2 3 4 5 6 7 8 9 |
import yaml with open('config.yaml') as f: try: dict = yaml.safe_load(f) print(dict) except yaml.YAMLError as e: print(e) |
That’s all about parsing a YAML file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)