The Wayback Machine - https://web.archive.org/web/20241120031942/https://www.geeksforgeeks.org/parse-a-yaml-file-in-python/
Open In App

Parse a YAML file in Python

Last Updated : 16 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

YAML is the abbreviation of Yet Another Markup Language or YAML ain’t markup Language which is the data format used to exchange data. YAML can store only data and no commands. It is similar to the XML and JSON data formats. In this article, we will dive deep into the concept of parsing YAML files in Python along with the example.

Parsing YAML Files in Python

PyYAML Module in Python Programming is considered as the Parser for Python. Using this library, we can perform different operations on the YAML files like reading or writing the YAML files. Serialization and Persisting YAML data can also be done using this PyYAML Module in Python.

For the usage of the PyYAML Module, we need to install it in Python by executing the below command:

pip install pyyaml

YAML files are saved using 2 different extensions, that are, .yaml and .yml. As we need to parse the YAML File, so we have created two YAML files which consist of data in the Key: Value pair. We will be taking the following YAML files as an example for our article.

geeksforgeek.yml

UserName: GeeksforGeeks
Password: GFG@123
Phone: 1234567890
Website: geeksforgeeks.org
Skills:
-Python
-SQL
-Django
-JavaScript

multi_docs.yml

---
UserName: GeeksforGeeks
Password: GFG@123
Phone: 1234567890
Website: geeksforgeeks.org
Skills:
-Python
-SQL
-Django
-JavaScript
...
---
UserName: Google
Password: google@123
Phone: 1234567890
Website: google.com
Skills:
-Python
-SQL
-Django
-JavaScript
...
---
UserName: Yahoo
Password: yahoo@123
Phone: 1234567890
Website: yahoo.com
Skills:
-Python
-SQL
-Django
-JavaScript

Now let us see a few methods using which we can parse a YAML file in Python.

Using load() Function

The yaml.load() function in the YAML module is used to read the YAML data or object into a Python Dictionary. There can be YAML data that consists of a huge number of key-value pairs (configuration files), so to read these files, the load() function can be helpful as it performs the deserialization of YAML data into Python. The Loader parameter of the load() function is set to SafeLoader, which intends to load the data of YAML safely. This is helpful in scenarios where the input is taken from untrusted sources.

Python3




import yaml
with open('geeksforgeeks.yml', 'r') as f:
    data = yaml.load(f, Loader=yaml.SafeLoader)
     
# Print the values as a dictionary
print(data)


Output:

{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123', 'Phone': 1234567890, 
'Website': 'geeksforgeeks.org', 'Skills': '-Python -SQL -Django -Javascript'}

Using full_load() Function

The yaml.full_load() function is used to parse the content of the YAML file in the form of key-value pairs. Then using the Python get() method, we can get specific data from the YAML file.

Python3




import yaml
with open('geeksforgeeks.yml', 'r') as f:
    data = yaml.full_load(f)
     
# Print the values as a dictionary
output = {
    'UserName': data.get('UserName'),
    'Password': data.get('Password'),
    'phone': data.get('Phone'),
    'Skills': ' '.join(data.get('Skills', []))
}
 
print(output)


Output:

{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123', 'phone': 1234567890, 
'Skills': '- P y t h o n - S Q L - D j a n g o - J a v a s c r i p t'}

Using safe_load() Function

Another way to load the YAML file in Python is by using the safe_load() method. It can be used in place of the load() method’s SafeLoader parameter, when the data is loaded from an untrusted source.

Python3




import yaml
 
with open('geeksforgeeks.yml') as f:
    dict = yaml.safe_load(f)
    print(dict)


Output:

{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123 *', 'phone': 987909890, 
'website': 'geeksforgeeks.org',
'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}

Using load_all() Function

The load_all() method is used when we want to load a YAML document present in a single file. The Loader parameter of the load() function is set to SafeLoader, which intends to load the data of YAML safely. This is helpful in scenarios where the input is taken from untrusted sources.

Python3




import yaml
 
from yaml.loader import SafeLoader
# open yaml file in read
 
with open('multiple_documents.yml', 'r') as f:
    yaml_data = list(yaml.load_all(f, Loader=SafeLoader))
    print(yaml_data)


Output:

[{'UserName': 'GeeksforGeeks', 'Password': 'GFG@123', 'Phone': 1234567890, 
'Website': 'geeksforgeeks.org', 'Skills': '-Python -SQL -Django -Resst Framework -Javascript'},
{'UserName': 'Google', 'Password': 'google@123', 'Phone': 1234567890,
'Website': 'google.com', 'Skills': '-Python -SQL -Django -Resst Framework -Javascript'},
{'UserName': 'Yahoo', 'Password': 'yahoo@123', 'Phone': 1234567890,
'Website': 'yahoo.com', 'Skills': '-Python -SQL -Django -Resst Framework -Javascript'}]



Similar Reads

Reading and Writing YAML File in Python
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 st
3 min read
How to parse local HTML file in Python?
Prerequisites: Beautifulsoup Parsing means dividing a file or input into pieces of information/data that can be stored for our personal use in the future. Sometimes, we need data from an existing file stored on our computers, parsing technique can be used in such cases. The parsing includes multiple techniques used to extract data from a file. The
5 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
How to Parse and Modify XML in Python?
XML stands for Extensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet. Note: For more information, refer to XML | Basics Here we consider that the XML file is present in th
4 min read
Python | How to Parse Command-Line Options
In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv). Parsing command line arguments using Python argparse module The argparse module can be used to parse command-line options. This module provides a very user-friendly syntax to define input of positional and keyword argume
3 min read
Python | Execute and parse Linux commands
Prerequisite: Introduction to Linux Shell and Shell Scripting Linux is one of the most popular operating systems and is a common choice for developers. It is popular because it is open source, it's free and customizable, it is very robust and adaptable. An operating system mainly consists of two parts: The kernel and the Shell. The kernel basically
6 min read
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}
4 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
2 min read
Parse XML using Minidom in Python
DOM (document object model) is a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the help of xml.dom.minidom, which is the minimal implementation of the DOM interface. It is simpler than the full DOM API and should be considered as smaller. Steps for Pa
1 min read
How to parse boolean values with `argparse` in Python
Command-line arguments are a powerful feature of many programming languages, including Python. They allow developers to specify options or parameters when running a script, making it more flexible and customizable. However, the process of parsing these arguments can be a tedious and error-prone task if done manually. The 'argparse' module in Python
5 min read
How to parse XML and count instances of a particular node attribute in Python?
In this article, we will see how to parse XML and count instances of a particular node attribute in Python. What is XML? Extensible Markup Language (XML) Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is a markup language like
3 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can split a string into smaller parts using the split()
5 min read
How To Use Python To Parse Server Log Files
Server log files are an invaluable source of information for system administrators and developers. They contain records of various events and activities that occur on a server, such as requests, errors, warnings, and more. Parsing these log files can provide insights into system performance, security issues, and user behavior. What is Parsing Serve
4 min read
How to Parse a Time String Containing Milliseconds in Python?
In many applications, precise timekeeping is crucial, and that often includes parsing time strings down to the millisecond. Python offers robust tools for handling date and time data, making this task straightforward. This article will guide us through the process of parsing time strings containing milliseconds using Python's datetime module. Under
3 min read
How to Search the Parse Tree using BeautifulSoup?
Searching the parse tree means we need to find the tag and the content of the HTML tree. This can be done in many ways. But the most used method for searching the parse tree is the find() and find_all() method. With the help of this, we can parse the HTML tree using Beautifulsoup. For Searching the parse tree follow the below steps. Step 1: For scr
2 min read
How to use Scrapy to parse PDF pages online?
Prerequisite: Scrapy, PyPDF2, URLLIB In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2. PyPDF2 is a pdf parsing library of python, which provides various methods like reader methods, writer methods, and many mor
3 min read
Pyspark - Parse a Column of JSON Strings
In this article, we are going to discuss how to parse a column of json strings into their own separate columns. Here we will parse or read json string present in a csv file and convert it into multiple dataframe columns using Python Pyspark. Example 1: Parse a Column of JSON Strings Using pyspark.sql.functions.from_json For parsing json string we'l
4 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
How to convert a PDF file to TIFF file using Python?
This article will discover how to transform a PDF (Portable Document Format) file on your local drive into a TIFF (Tag Image File Format) file at the specified location. We'll employ Python's Aspose-Words package for this task. The aspose-words library will be used to convert a PDF file to a TIFF file. Aspose-Words: Aspose-Words for Python is a pot
3 min read
MoviePy – Getting Original File Name of Video File Clip
In this article we will see how we can get the original file name of the video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Original file name is the name of the original video that existed in the first place i.e which was loaded, even after altering and editing of the vi
2 min read
PYGLET – Opening file using File Location
In this article we will see how we can open a file using file location object in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set t
3 min read
PyCairo - Saving SVG Image file to PNG file
In this article, we will see how we can save an SVG file to a PNG file using PyCairo in Python. We can create an SVG file using SVGSurface method. An SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files ar
2 min read
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
How to get Scrapy Output File in XML File?
Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population by country data from worldometers website. Let's i
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg