• 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 YAML to INI in Python

Convert YAML to INI in Python

Author: Aditya Raj
Last Updated: March 29, 2023

We use YAML and INI files to store configuration data. This article discusses how to convert a yaml file or string to an INI file in Python.

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

What is YAML File Format?

The YAML file format is a human-readable data serialization format. It is often used for configuration files and data exchange between softwares. YAML files are structured using whitespacea, colon character and indentation.

A YAML file consists of key-value pairs. Here, 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.

For instance, the following example represents data of an employee in the YAML format.

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 top-level key "employee" contains two key-value pairs. It has two inner keys namely "name" and "age". The "name" key has value "John Doe" and the "age" key has the value "35".
  • "job" key contains three key-value pairs. The "title" key has the value "Software Engineer". "department" key has the value "IT" and the "years_of_experience" key has the value 10.
  • The "address" key contains five key-value pairs. "street" key has the value "123 Main St.". "city" key has the value "San Francisco". “state” key has a value "CA". and the "zip" key has the value "94102".

We often use YAML format as an alternative to JSON and XML because it is easier to read and write by humans. It also supports more complex data structures than simpler file formats such as INI format.

What is INI File Format?

An INI file is a text-based format commonly used to store configuration data for software applications.

INI files are organized into sections. Each section contains a set of key-value pairs that define various settings or parameters. We define each section within square brackets ([]) with the name of the section enclosed within the brackets.

Within each section, key-value pairs are specified in the format "key=value". The key represents the name of a configuration setting, and the value represents the value assigned to that setting.

We can represent the data shown in the previous example using the INI 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

We mainly use INI files on Windows-based systems and many applications as a simple and easy-to-use configuration file format. However, in recent years, the INI file format has been replaced by more modern formats like JSON, XML, and YAML.

YAML String to INI File in Python

To convert a yaml string to an INI file in python, we will use the yaml module and the configparser module. 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. The ConfigParser object is used to store the data in the INI file format. 
  • Next, we will open an empty INI file in write mode using the open() function. The open() function takes the file name as its first input argument and the python literal “w” as its second input argument. After execution, it returns a file pointer.
  • Now we will convert the YAML string to a python dictionary using the load() method defined in the yaml module. The load() method takes the yaml string as its first input argument and the loader type in its Loader parameter. After execution, it returns a python dictionary. We will use the SafeLoader input argument for the Loader parameter.
  • Once we get the dictionary from the yaml string, we will convert it to INI file format and save it in the configuration file using the add_section() and set() methods defined in the configparser module. You can read more about how to convert a dictionary to INI format in this article on converting a python dictionary to INI format in Python.
  • After loading the data from the dictionary to the configparser object, we will use the write() method to save the ini file to the disk. The write() method, when invoked on a ConfigParser object, takes the file pointer to the INI file as its input and writes the data to the INI file.
  • Finally, we will close the INI file using the close() method.

After executing the above steps, we can easily convert a yaml string to an ini file in python. You can observe this in the following example.

import configparser
import yaml
from yaml import SafeLoader
file =open("employee1.ini","w")
config_object = configparser.ConfigParser()
yaml_string="""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'"""
python_dictionary=yaml.load(yaml_string, Loader=SafeLoader)
for section, options in python_dictionary.items():
    config_object.add_section(section)
    for key, value in options.items():
        config_object.set(section, key, str(value))
config_object.write(file)
file.close()

The output file looks as follows.

Output INI File
Output INI File

YAML File to INI File in Python

Instead of the yaml string, we can also convert a yaml file to an ini file in python. Consider that we have the following yaml file.

YAML File
YAML File

To convert this YAML file to a INI file, we will use the following steps.

  • First, we will open the yaml file in read mode using the open() function. We will also open an INI file in write to save the output file. Additionally, we will create an empty ConfigParser object to store the data for the ini file.
  • Next, we will load the yaml file into a python dictionary using the load() method. Here, the load() method takes the pointer to the yaml file as its first input argument and the loader type in its Loader parameter. After execution, it returns the python dictionary.
  • Once we get the python dictionary, we will convert it to ini format and save it in the ConfigParser object as discussed in the previous section.
  • After loading the data from the dictionary to the ConfigParser object, we will use the write() method to save the ini file to the disk. 
  • Finally, we will close the files using the close() method.

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

import configparser
import yaml
from yaml import SafeLoader
file =open("employee1.ini","w")
yaml_file =open("employee1.yaml","r")
config_object = configparser.ConfigParser()
python_dictionary=yaml.load(yaml_file, Loader=SafeLoader)
for section, options in python_dictionary.items():
    config_object.add_section(section)
    for key, value in options.items():
        config_object.set(section, key, str(value))
config_object.write(file)
file.close()
yaml_file.close()

The output INI file of the above code will be same as the previous example.

Conclusion

In this article, we discussed how to convert a yaml file or string to INI format in Python. To learn more about file conversion, you can read this article on how to convert yaml to xml in python. You might also like this article on custom JSON decoders 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