Python read INI file configuration example

In this tutorial you will learn how to read ini configuration file in php, how to use python configparser to read write configuration file!

Here we see how to work with ini file in python application, here are few points to learn:

  • How to create INI file, and create new configuration section in INI file.
  • Defining key values in INI file with different data types
  • Reading values from INI file with different built-in methods
  • Writing to INI file from python application

Read Configuration using ConfigParser

Python Configuration File Example

Ini is basically a plain text file with .ini extension, this is how your mypy.ini file may look like

# Specify additional search paths for Mypy
#mypy_path = stubs

# Increase strictness of checks
disallow_any_decorated = True
disallow_any_expr = True
disallow_any_generics = True
disallow_subclassing_any = True
disallow_untyped_defs = True
disallow_untyped_calls = True
strict_optional = True
warn_no_return = True

# Display statistics after running
#dump_type_stats = True
#dump_inference_stats = False
# Ignore errors in 'tests' directory
#ignore_errors = True


Notice all values are written in plain text format, even string values are without "double quote", anything within box bracket indicates a new section like "[dbinfo]"

Reading config values with ConfigParser

Now you learn how to read configuration values from INI file in python class

  1. Import ConfigParser class reference
  2. Create a new instance of ConfigParser class
  3. Specify the file name you want to Read

Once you have ConfigParser object ready, now you can read any key with built in-method, Note: for different data type there are different methods, for example .get method for string data type and .getint method for integer data type.

So the python code for reading will look like.

value = config.get('section-name', 'key')

from configparser import ConfigParser
class StudentDTO():        
    def __init__(self):
        config = ConfigParser()'mypy.ini')
        database = config.get('dbinfo', 'database')
        dbusername = config.get('dbinfo', 'dbusername')
        dbpassword = config.get('dbinfo', 'dbpassword')
        dbhost = config.get('dbinfo', 'dbhost')

If you are reading from "appconfig.json" file, then please refer the code below.

import pymysql
import os
import json

def load_AppSetting(json_file="appconfig.json"):
    with open(json_file) as f:
        setting = json.load(f)
    return setting["dbinfo"]

apikey = load_AppSetting()

Now we see how to write ini file in python using ConfigParser

How to read INI configuration file in Python
Learn python programming with free python coding tutorials.
Other Popular Tutorials
Read Write in INI file
Python programming examples | Join Python Course