• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert INI to YAML in Python

Convert INI to YAML in Python

Author: Aditya Raj
Last Updated: March 31, 2023

INI and YAML file formats are used to store configuration files. This article discusses how to convert an INI file to yaml format in Python.

Table of Contents
  1. What is the INI file format?
  2. What is the YAML file format?
  3. Convert INI File to YAML String in Python
  4. Convert INI File to YAML File in Python
  5. Conclusion

What is the INI file format?

INI (initialization) files are a simple and widely used configuration file format that we use to store data in a plain text format. 

The INI format consists of different sections enclosed in square brackets. Each section is followed by a list of key-value pairs and has its own set of key-value pairs. The keys and their values are separated by an equal sign.

For example, consider the following INI file.

[employee]
name=John Doe
age=35

[job]
title=Software Engineer
department=IT
years_of_experience=10

[address]
street=123 Main St.
city=San Francisco
state=CA
zip=94102

The above INI file contains three sections: [employee], [job], and [address]. Each section has its own set of key-value pairs.

  • In the [employee] section, the key "name" has the value "John Doe", and the key "age" has the value "35".
  • The [job] section contains the key "title" with value "Software Engineer", the key "department" with value "IT", and the key "years_of_experience"with value "10".
  • In the [address] section, the key "street" has the value "123 Main St.", the key "city" has the value "San Francisco", the key "state" has the value "CA", and the key "zip" has the value "94102".

We typically use INI files for configuration files for applications and operating systems. INI files are easy to read and write and we can edit them with a simple text editor. However, INI files are limited in their capabilities. They have been largely replaced by more advanced formats such as JSON, YAML and XML.

What is the YAML file format?

YAML is a human-readable data serialization language. It is often used for configuration files and data exchange between softwares. YAML files are structured using whitespace and indentation.

Each YAML files consist of key-value pairs, where the key is separated from the value by a colon and a space. The key-value pairs can be nested to create more complex data structures such as lists and dictionaries.

We can represent the data shown in the INI format using the YAML format as shown below.

employee:
  name: John Doe
  age: '35'
job:
  title: Software Engineer
  department: IT
  years_of_experience: 10
address:
  street: 123 Main St.
  city: San Francisco
  state: CA
  zip: '94102'

In this example, the YAML file contains three top-level keys: "employee”, "job", and "address". Each of these keys contains a set of key-value pairs that represent the data associated with that key.

YAML files can also include comments, which begin with the “#” character and continue until the end of the line.

YAML is often used as an alternative to JSON, INI, and XML. It is easier to read and write by humans, and supports more complex data structures. It is widely used in configuration files for applications, particularly those written in Ruby, and Python.

Convert INI File to YAML String in Python

To convert an INI file to a YAML string, we will use the configparser module and the yaml module. For instance, consider the following INI file.

Input INI File
Input INI File

We will convert the above ini file to yaml string. For this, we will use the following steps.

  • First, we will create an empty ConfigParser object using the ConfigParser() function defined in the configparser module. 
  • Next, we will open the INI file in read mode using the open() function. The open() function takes the file name as its first input argument and the python literal “r” as its second input argument. After execution, it returns a pointer to the file.
  • Now, we will load the ini file to the ConfigParser object using the read_file() method. The read_file() method, when invoked on the empty ConfigParser object, takes the file pointer to the INI file as its input argument and loads the file to the ConfigParser object. 
  • Next, we will convert the ConfigParser object to a python dictionary as discussed in this article on how to convert an INI file to a python dictionary.
  • Once we get the python dictionary from the ini file, we will use the dump() method defined in the yaml module to convert the python dictionary to the yaml file. The dump() method takes the python dictionary as its input argument and returns the yaml string after execution.

Using the above steps, we can easily convert an INI file to a yaml string as shown below.

import configparser
import yaml
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
config_object.read_file(file)
output_dict=dict()
sections=config_object.sections()
for section in sections:
    items=config_object.items(section)
    output_dict[section]=dict(items)
yaml_string=yaml.dump(output_dict)
print("The output YAML string is:")
print(yaml_string)

Output:

The output YAML string is:
address:
  city: San Francisco
  state: CA
  street: 123 Main St.
  zip: '94102'
employee:
  age: '35'
  name: John Doe
job:
  department: IT
  title: Software Engineer
  years_of_experience: '10'

Convert INI File to YAML File in Python

Instead of converting it to a yaml string, we can also convert an INI file to a YAML file in python. For this, we can use the following steps.

  • First, we will convert the INI file to a python dictionary as shown in the previous example.
  • Next, we will open an empty YAML file in write mode to store the output. For this, we will use the open() function.
  • Once we have the python dictionary created from the INI file and the file pointer to the YAML file, we will use the dump() method defined in the yaml module to convert the dictionary to the yaml file. The dump() method takes the dictionary as its first argument and the file pointer to the yaml file as its second input argument. After execution, it writes the contents of the python dictionary in the yaml format to the file. 
  • Finally, we will close the files using the close() method.

After executing the above steps, we can easily convert an INI file to a YAML file. You can observe this in the following example.

import configparser
import yaml
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
yaml_file =open("employee.yaml","w")
config_object.read_file(file)
output_dict=dict()
sections=config_object.sections()
for section in sections:
    items=config_object.items(section)
    output_dict[section]=dict(items)
yaml.dump(output_dict,yaml_file)
yaml_file.close()
file.close()

The output yaml file looks as follows.

Output YAML File
Output YAML File

Conclusion

In this article, we discussed how to convert an INI file to YAML format in Python. To learn more about programming, you can read this article on how to convert YAML to INI in Python. You might also like this article on custom JSON encoders in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us