Free Web Development Online Tutorials, Learn to Code
How To Use Python ConfigParser To Read Write Configuration File, Read INI file in Python

Python read configuration file example

In this tutorial you will learn how to read ini configuration file in php

Read Configuration using ConfigParser

How To Use Python ConfigParser To Read Write Configuration File!

In this tutorial you will learn 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

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')

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

How to read INI configuration file in Python

Read Write in INI file
Python programming examples | Join Python Course