Reading and Writing YAML File in Python
Last Updated :
13 Sep, 2024
YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is commonly used for configuration files and data exchange between languages with different data structures. YAML is preferred in many cases due to its simplicity and readability compared to other formats like JSON or XML. In Python, working with YAML files is straightforward thanks to the PyYAML
library. This article guides us through reading from and writing to YAML files using Python.
Installing PyYAML
Before we start, make sure we have the PyYAML library installed. We can install it using pip:
pip install pyyaml
Writing Data to a YAML File in Python
Let's start by writing some data to a YAML file. We will create a Python dictionary and then save it as a YAML file.
Python
import yaml
# Data to be written to the YAML file
data = {
'name': 'Amit',
'age': 25,
'city': 'Mumbai',
'skills': ['Python', 'Data Analysis', 'Machine Learning']
}
# Writing the data to a YAML file
with open('data.yaml', 'w') as file:
yaml.dump(data, file)
print("Data has been written to 'data.yaml'")
Output:
Data has been written to 'data.yaml'
writing to yaml file in PythonReading Data from a YAML File in Python
Now, let's read the data from the YAML file we just created.
Python
import yaml
# Reading data from the YAML file
with open('data.yaml', 'r') as file:
loaded_data = yaml.safe_load(file)
print("Data read from 'data.yaml':")
print(loaded_data)
Output:
Reading from YAML file in Python
Reading YAML with Nested Structures
YAML files can also have nested structures like dictionaries within dictionaries. Let’s look at an example of reading a more complex YAML file.
Example YAML (nested_data.yaml):
person:
name: Raj
details:
age: 30
city: Delhi
skills:
- HTML
- CSS
- JavaScript
Python Code to Read Nested YAML:
Python
import yaml
# Reading nested data from a YAML file
with open('nested_data.yaml', 'r') as file:
nested_data = yaml.safe_load(file)
print("Nested Data read from 'nested_data.yaml':")
print(nested_data)
Output:
Nested Data read from 'nested_data.yaml':
{'person': {'name': 'Raj', 'details': {'age': 30, 'city': 'Delhi', 'skills': ['HTML', 'CSS', 'JavaScript']}}}
Writing Nested Data to a YAML File
We can also write nested data structures back to a YAML file:
Python
import yaml
# Nested data
nested_data = {
'person': {
'name': 'Sita',
'details': {
'age': 28,
'city': 'Kolkata',
'skills': ['Data Science', 'SQL', 'TensorFlow']
}
}
}
# Writing nested data to a YAML file
with open('nested_data.yaml', 'w') as file:
yaml.dump(nested_data, file)
print("Nested data has been written to 'nested_data.yaml'")
Output:
Nested data has been written to 'nested_data.yaml'
Writing nested data to YAML in PythonConclusion
YAML is a flexible and human-readable data format, making it ideal for configuration files and data exchange. With the PyYAML
library, Python developers can easily read from and write to YAML files, making it simple to integrate YAML into their projects. Whether we're handling simple configuration settings or complex data structures, PyYAML
provides the tools we need to work effectively with YAML in Python.
By understanding how to read and write YAML files in Python, we can take advantage of YAML's simplicity and power in our own projects.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read