![]() |
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. What is Python yaml Module?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 PyYAML YAML Module in PythonBelow are some of the examples by which we can understand about YAML module in Python: Parsing YAML from a Filehorje.yml UserName: GeeksforGeeks 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, Serializing Python Objects to YAMLHere, 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 Handling Multi-Document YAML FilesIn 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} Serializing Python Objects with Custom FormattingPython 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 |
Reffered: https://www.geeksforgeeks.org
Python Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |