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 Python
Below are some of the examples by which we can understand about YAML module in Python:
Parsing YAML from a File
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.
Python3
import yaml
# YAML file path
yaml_file = 'geeksforgeeks.yml'
# Reading YAML data from file
with open(yaml_file, 'r') as f:
yaml_data = yaml.load(f, Loader=yaml.FullLoader)
# Displaying parsed YAML data
print(yaml_data)
Output:
{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123', 'Phone': 1234567890,
'Website': 'geeksforgeeks.org', 'Skills': '-Python -SQL -Django -Javascript'}
Serializing Python Objects to YAML
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.
Python3
import yaml
# Python dictionary
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Serializing dictionary to YAML format
yaml_data = yaml.dump(data)
# Displaying YAML data
print(yaml_data)
Output:
age: 30
city: New York
name: John
Handling Multi-Document YAML Files
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.
Python3
import yaml
# Multi-document YAML string
yaml_string = """
name: John
age: 30
---
name: Alice
age: 25
"""
# Parsing multi-document YAML string
yaml_data = yaml.load_all(yaml_string, Loader=yaml.FullLoader)
# Displaying parsed YAML data
for doc in yaml_data:
print(doc)
Output:
{'name': 'John', 'age': 30}
{'name': 'Alice', 'age': 25}
Serializing Python Objects with Custom Formatting
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.
Python3
import yaml
# Python dictionary
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Serializing dictionary to YAML format with custom formatting
yaml_data = yaml.dump(data, default_flow_style=False)
# Displaying YAML data
print(yaml_data)
Output:
age: 30
city: New York
name: John
Similar Reads
Python sys Module
The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. Let's consider the
6 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python Typer Module
Typer is a library for building powerful command-line interface applications in the easiest way. It is easier to read and the simplest way to create a command line application rather than using the standard Python library argparse, which is complicated to use. It is based on Python 3.6+ type hints a
5 min read
Python String Module
The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines vario
4 min read
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Python Module Index
Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
Reloading modules in Python
The reload() is a previously imported module. If you've altered the module source file using an outside editor and want to test the updated version without leaving the Python interpreter, this is helpful. The module object is the return value. Reloading modules in Python2.xreload(module)For above 2.
1 min read
Python subprocess module
The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. In this tutorial, weâll delve into how to effective
9 min read
llist module in Python
Up until a long time Python had no way of executing linked list data structure. It does support list but there were many problems encountered when using them as a concept of the linked list like list are rigid and are not connected by pointers hence take a defined memory space that may even be waste
3 min read