Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Reading INI Configuration Files with Python for API Automation

Tech 1

1. Structure of an INI File

An INI file consists of multpile sections, each storing data in key=value format.

INI file structure

2. Reading INI File Data with Python

2.1 Import the Module

import configparser
config = configparser.ConfigParser()  # Instantiate the class

# Define file path
path = './Config.ini'

2.2 Read File Content

# Method 1: Using read()
config.read(path)
value = config['select']['url']
print('Method 1 value:', value)

# Method 2: Using get()
value = config.get('select', 'url')
print('Method 2 value:', value)

# Method 3: Get all key-value pairs from a section
value = config.items('select')
print('Method 3 value:', value)

Output:

Output screenshot

2.3 Reading Typed Data

The methods above return all data as strings. To get specific data types, use:

  • getint()
  • getfloat()
  • getboolean()
value = config.getint('connect_mysql', 'port')
print('Typed value:', value)
print('Type:', type(value))

Typed data output

2.4 Writing Data to a INI File

config.add_section('login')  # Add a new section
config.set('login', 'username', 'admin')  # Write key-value
config.set('login', 'password', '123456')
config.write(open(path, 'a'))  # Save to file

Write output

2.5 Get All Sections

sections = config.sections()
print(sections)

Sections output

3. ConfigParser Wrapper Class

For better reusability, we wrap commmon methods into a utility class.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Utility class for configuration file operations
"""

import configparser


class ConfigUtil:

    def __init__(self):
        self.config = configparser.ConfigParser()

    def read(self, filename):
        """
        Read configuration file
        :param filename: path to the configuration file
        """
        self.config.read(filename, encoding="utf-8-sig")

    def get_value(self, section, option):
        """
        Get value of a specific option from a section
        :param section: section name
        :param option: option key
        :return: value or None if not found
        """
        try:
            return self.config[section][option]
        except Exception:
            print("Value not found")
            return None

    def get_section_items(self, section):
        """
        Get all key-value pairs from a section as list of tuples
        :param section: section name
        :return: list of (key, value) tuples
        """
        return self.config.items(section)

    def get_all_sections(self):
        """
        Get all section names
        :return: list of section names
        """
        return self.config.sections()

    def get_options_in_section(self, section):
        """
        Get all option names in a section
        :param section: section name
        :return: list of option names
        """
        return self.config.options(section)

    def has_section(self, section):
        """
        Check if a section exists
        :param section: section name
        :return: bool
        """
        return section in self.config

    def has_option(self, section, option):
        """
        Check if an option exists in a section
        :param section: section name
        :param option: option key
        :return: bool
        """
        return option in self.config[section]

    def get_typed_value(self, section, option, data_type="int"):
        """
        Get value with specified type
        :param section: section name
        :param option: option key
        :param data_type: "int", "float", or "boolean"
        :return: typed value
        """
        if data_type == "int":
            return self.config.getint(section, option)
        elif data_type == "float":
            return self.config.getfloat(section, option)
        elif data_type == "boolean":
            return self.config.getboolean(section, option)
        else:
            raise ValueError("Unsupported data type")

    def write_option(self, section, key, value, path):
        """
        Write a key-value to the INI file
        :param section: section name
        :param key: option key
        :param value: option value
        :param path: file path
        """
        if section is None:
            return
        self.config.add_section(section)  # Add section if not exists?
        self.config.set(section, key, value)
        with open(path, 'a') as configfile:
            self.config.write(configfile)


if __name__ == '__main__':
    util = ConfigUtil()
    file_path = './server.ini'
    util.read(file_path)
    print(util.get_value('select', 'broswer'))
    print(util.get_section_items('select'))
    print(util.get_all_sections())
    print(util.get_options_in_section('connect_mysql'))
    print(util.has_section('login'))
    print(util.has_option('login', 'username'))
    print(util.get_typed_value('connect_mysql', 'port', 'int'))
    util.write_option('TEST01', 'USER', 'cs01', file_path)

Output:

Wrapper class output 1

Wrapper class output 2

Tags: PythonINI

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.