Read and write configuration file (.ini format) in python

There are several file formats you can use for your configuration file, the most commonly used format are .ini, .json and .yaml. In this article, I will sharing with you how to read/write your configurations in the .ini file formats.

Below is a example of the ini file, you can define the sections (e.g. [LOGIN]) as much as you want to separate the different configuration info.

[LOGIN] 
user = admin
#Please change to your real password
password = admin
[SERVER]
host = 192.168.0.1
port = 8088

In python, there is already a module configparser to read an parse the information from the ini file int dictionary objects. Assume you have saved above as config.ini file into your current folder, you can use the below lines of code to read.

import configparser config = configparser.ConfigParser() config.read("config.ini") login = config['LOGIN'] server = config['SERVER']

You can assign each of the sections into a separate dictionary for easier accessing the values. The output should be same as below:

Note that the line starting with # symbol (or ; ) will be taken as comment line and omitted when parsing the keys and values.

Also all the values are taken as string, so you will need to do your own data type conversion after you read it.

Now let’s see how we can write to an ini file.

You will still need this configparser library, and the idea is that you need to set the keys and values into the configparser object and then save it into a file.

config = configparser.ConfigParser() if not config.has_section("INFO"): config.add_section("INFO") config.set("INFO", "link", "www.codeforests.com") config.set("INFO", "name", "ken") with open("example.ini", 'w') as configfile: config.write(configfile)

And this would create the example.ini file with below content:

[INFO] 
link = www.codeforests.com
name = ken

I have created another two separate articles to cover the .json and .yaml format, please have a look if you are interested.

As per always, welcome any comments or questions.

Originally published at https://www.codeforests.com on June 14, 2020.

--

--

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
codeforests

Resources and tutorials for python, data science and automation solutions