![]() |
VOOZH | about |
YAML (YAML Ain't Markup Language) is a human-readable data serialization format that is commonly used for configuration files, data exchange, and more. Python provides a convenient module called yaml for parsing and serializing YAML data. In this article, we will understand the yaml module, discuss its features, and provide illustrative examples of its usage.
The yaml module in Python provides functions for parsing YAML data into Python objects (yaml.load()) and serializing Python objects into YAML format (yaml.dump()). It supports various YAML features, including mappings, sequences, and scalars.
We can install the Python YAML module by using the following command:
pip install PyYAMLBelow are some of the examples by which we can understand about YAML module in Python:
geeksforgeeks.yml
UserName: GeeksforGeeks
Password: GFG@123
Phone: 1234567890
Website: geeksforgeeks.org
Skills:
-Python
-SQL
-Django
-JavaScript
In this example, we use yaml.load() to parse YAML data from a file. The Loader=yaml.FullLoader argument is used to load the YAML data securely.
Output:
{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123', 'Phone': 1234567890,
'Website': 'geeksforgeeks.org', 'Skills': '-Python -SQL -Django -Javascript'}
Here, we use yaml.dump() to serialize a Python dictionary into YAML format. The resulting YAML data can be written to a file or used elsewhere as needed.
Output:
age: 30
city: New York
name: John
In this example, we use yaml.load_all() to parse a multi-document YAML string. Each document in the string is parsed individually, and we iterate through the parsed data to display each document.
Output:
{'name': 'John', 'age': 30}
{'name': 'Alice', 'age': 25}
Python yaml.dump() serialize a Python dictionary into YAML format with custom formatting. Setting default_flow_style=False ensures that the YAML output uses a block style instead of inline style for sequences and mappings.
Output:
age: 30
city: New York
name: John