This tutorial explains about how to read and write an ini file in Python.

You can check more about ini file tutorials .

configparser is a Python module for Configuration file parser for Windows ini files.

How to parse or read ini file content in Python

Let’s define the ini file for reading.

config.ini

; Application Configuration Settings

[Database]
; Database server address
server = localhost

; Database port number
port = 3306

[User]
; Admin username
username = admin

; Admin password (avoid including actual passwords in comments!)
password = secret

 ; Application Settings

[application]
host = "localhost"
port = 8080

[database]
hostname = "localhost:3201"
; database username

user = "admin"
; database password, not recommended
password = "secretpassword"

Following are steps to read an ini file in Python using configparser

  • Import configparser into a code
  • Create a config object that stores the sections, keys, and value pair using the ConfigParser() function
  • Next, read the ini file using the read() method, and store the content in the config variable.
  • You can check multiple ways to read the values
    • sections(): returns an array of sections
    • config.get(section, key): Optional section parameter, if provided, returns the key in a section
    • Another way using config[section][key] syntax
    • you can also use for loop to iterate all keys or keys in a section

Here is an example

import configparser

config = configparser.ConfigParser()
config.read('config.ini')
# List out all sections
sections= config.sections()
print(sections) # ['Database', 'User', 'application', 'database']
# One way to read key value
hostname = config.get('database', 'hostname')
print(hostname)
# Second way to read key value
username = config['database']['username']
print(username)

# Convert the given value to a different type of int

port = int(config['application']['port'])
print(port)
# Iterate keys using for loop
for key in config['database']:
  print(key)

Check key exists in ini file in Python

The in operator is used to check section or key exists in a config object.

It returns the Boolean value True( if exists) or False(not exists). It can be used in condition-if statements and can set a default value if not exist.

Syntax:

the section in config  # checks if the section exists or not in the config
key in config # checks if the key exists or not in config
key in config[`section`] # checks if the key exists or not in a specific section

Below checks if a given section or key exists in a section.

import configparser

config = configparser.ConfigParser()
config.read('config.ini')
# Check section and key exists
if 'database' in config and 'hostname' in config['database']:
  hostname1 = config['database']['hostname']
else:
  hostname1 = 'localhost'

print(hostname)
print('database' in config) # True

print('database1' in config) # False

How to write python object to ini file

This example creates a python object and creates an ini file from an object.

  • Import configparser into a first line
  • Create a config object
  • Set the value pair into the config object
  • create a file with write access and write the object to the file using the write() method
import configparser
config = configparser.ConfigParser()
config['database'] = {'hostname': 'localhost','username': 'root','password':'secret'
}

with open('result.ini', 'w') as configfile:
    config.write(configfile)

By RUnning above code, result.ini file was created with the below content

[database]
hostname = localhost
username = root
password = secret

To update a key and values to a given section, you can use config.set() method

config.set('database', 'hostname', 'qa4.localhost')

Here is an example to update the value for a given key and section

import configparser
config = configparser.ConfigParser()

config.read('result.ini')
config.set('database', 'hostname', 'qa4.localhost')


with open('result.ini', 'w') as configfile:
    config.write(configfile)