- How To Use Python ConfigParser To Read Write Configuration File
- 1. Python Configuration File Example.
- 2. Read Configuration File.
- 2.1 Read Single Configuration File.
- 2.2 Read Multiple Configuration File.
- 3. Configuration File Sections And Options Operation Method.
- 3.1 sections(), options(section_name) and items(section_name) method.
- 3.2 has_section(section_name), has_option(section_name, option_name) method.
- 4. Modify Configuration File Section And Option Values.
- 4.1 Add Section And Options Then Write To File.
- 4.2 Edit Section And Option Values.
- 4.3 Remove Section And Options.
- Python ConfigParser
- Python ConfigParser
- Python ConfigParser read file
- Python ConfigParser sections
- Python ConfigParser read from string
- Python ConfigParser read from dictionary
- Python ConfigParser write
- Python ConfigParser interpolation
- Author
How To Use Python ConfigParser To Read Write Configuration File
Configuration file in python is a text file which contains section and seciton’s options. The file extension is .ini. This is same with windows .ini file. One configuration file can contains multiple sections. And python configparser.ConfigParser class provide methods to read, write, update and remove the .ini file content. This article will show you some examples.
1. Python Configuration File Example.
Below content contains two section, the section name begins with [ and ends with ]. The options are saved in key value pair format.
[mysql_conn_data] host=localhost database=dev2qa [account] user_name=jerry password=888888
2. Read Configuration File.
2.1 Read Single Configuration File.
Support we save above configuration data in file /home/jerry/config_file_1.ini. Then we can use ConfigParser class’s get(section_name, option_key) method to get related option value.
# import ConfigParser class. >>> from configparser import ConfigParser # create an instance of ConfigParser class. >>> parser = ConfigParser() # read and parse the configuration file. >>> parser.read('/home/jerry/config_file_1.ini') ['/home/jerry/config_file_1.ini'] # get option value in specified section. >>> mysql_conn_host = parser.get('mysql_conn', 'host') # print the option value. >>> print(mysql_conn_host) localhost >>> account = parser.get('account', 'user_name') >>> >>> print(account) jerry
2.2 Read Multiple Configuration File.
Now we will create another configuration file /home/jerry/config_file_2.ini with below content. Below configuration file also cotains a [account] section which is same with config_file_1.ini.
[oracle_conn_data] host=2.2.2.2 database=orcl [account] user_name=orcl password=orcl888
Run below python source code. You will find the second config file [account] section data will be used because of same section name with config file 1.
>>> from configparser import ConfigParser >>> >>> parser = ConfigParser() >>> # add the two configuration file in a list object. >>> config_file_list = ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini'] >>> # read above list object to parse the two configuration files. >>> parser.read(config_file_list) ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini'] >>> >>> oracle_conn_host = parser.get('oracle_conn', 'host') >>> >>> print(oracle_conn_host) 2.2.2.2 >>> # the second configuration file's section will override the first configuration file same section value. >>> account = parser.get('account', 'user_name') >>> >>> print(account) orcl
3. Configuration File Sections And Options Operation Method.
3.1 sections(), options(section_name) and items(section_name) method.
The ConfigParser class provide sections(), options(section_name) and items(section_name) method to get all config file sections and options value. If multiple configure file contains same section name, then the second configure file’s section’s options will be used.
>>> from configparser import ConfigParser >>> >>> parser = ConfigParser() >>> >>> config_file_list = ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini'] >>> >>> parser.read(config_file_list) ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini'] >>> # get all sections. >>> for section in parser.sections(): # get current section's options. . options = parser.options(section) . print('Section', section, ' has ', options, ' options.') # get option's key and value item. . for key, value in parser.items(section): . print(key, ' = ', value) . Section mysql_conn has ['host', 'database'] options. host = localhost database = dev2qa Section account has ['user_name', 'password'] options. user_name = orcl password = orcl888 Section oracle_conn has ['host', 'database'] options. host = 2.2.2.2 database = orcl
3.2 has_section(section_name), has_option(section_name, option_name) method.
These two method will check whether the provided section, or option exist ot not.
>>> parser.has_section('mysql_conn') True >>> parser.has_option('mysql_conn', 'port') False
4. Modify Configuration File Section And Option Values.
4.1 Add Section And Options Then Write To File.
Please remember invoke file.close() method to save new configuration items to the target file at the coding end. Otherwise the file content will be empty.
# add a new section. >>> parser.add_section('hello') # add a new option in above section. >>> parser.set('hello', 'username', 'tom') # open a configuration file >>> file = open('/home/jerry/config_file_1.ini') # write the new section and options to the file. >>> parser.write(file) # do not forget close the file to flush the parser sections. >>> file.close() # you can also write the parser sections to system console to verify the section and option values. # do not forget import sys module, otherwise you will encounter NameError: name 'sys' is not defined >>> import sys >>> parser.write(sys.stdout) [mysql_conn] host = localhost database = dev2qa [account] user_name = orcl password = orcl888 [oracle_conn] host = 2.2.2.2 database = orcl [hello] username = tom
4.2 Edit Section And Option Values.
Use ConfigParser’s set(section_name, option_name, option_value) method to set section and option values.
>>> parser.set('account', 'user_name', 'test') >>> >>> parser.write(sys.stdout) [mysql_conn] host = localhost database = dev2qa [account] user_name = test password = orcl888 [oracle_conn] host = 2.2.2.2 database = orcl [hello] username = tom
4.3 Remove Section And Options.
ConfigParser’s remove_section(section_name), remove_option(section_name, option_name) method will remove section and options.
# remove [hello] section. >>> parser.remove_section('hello') True # remove 'password' option in [account] section. >>> parser.remove_option('account', 'password') True # check whether the remove action success or not. >>> parser.write(sys.stdout) [mysql_conn] host = localhost database = dev2qa [account] user_name = test [oracle_conn] host = 2.2.2.2 database = orcl
Python ConfigParser
Python ConfigParser tutorial shows how to work with configuration files in Python with ConfigParser.
Python ConfigParser
ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.
The configuration file consists of sections followed by key/value pairs of options. The section names are delimited with [] characters. The pairs are separated either with : or = . Comments start either with # or with ; .
Python ConfigParser read file
In the first example, we read configuration data from a file.
[mysql] host = localhost user = user7 passwd = s$cret db = ydb [postgresql] host = localhost user = user8 passwd = mypwd$7 db = testdb
We have two sections of configuration data.
#!/usr/bin/python import configparser config = configparser.ConfigParser() config.read('db.ini') host = config['mysql']['host'] user = config['mysql']['user'] passwd = config['mysql']['passwd'] db = config['mysql']['db'] print('MySQL configuration:') print(f'Host: ') print(f'User: ') print(f'Password: ') print(f'Database: ') host2 = config['postgresql']['host'] user2 = config['postgresql']['user'] passwd2 = config['postgresql']['passwd'] db2 = config['postgresql']['db'] print('PostgreSQL configuration:') print(f'Host: ') print(f'User: ') print(f'Password: ') print(f'Database: ')
The example reads configuration data for MySQL and PostgreSQL.
config = configparser.ConfigParser() config.read('db.ini')
We initiate the ConfigParser and read the file with read .
host = config['mysql']['host'] user = config['mysql']['user'] passwd = config['mysql']['passwd'] db = config['mysql']['db']
We access the options from the mysql section.
host2 = config['postgresql']['host'] user2 = config['postgresql']['user'] passwd2 = config['postgresql']['passwd'] db2 = config['postgresql']['db']
We access the options from the postgresql section.
$ python reading_from_file.py MySQL configuration: Host: localhost User: user7 Password: s$cret Database: ydb PostgreSQL configuration: Host: localhost User: user8 Password: mypwd$7 Database: testdb
Python ConfigParser sections
The configuration data is organized into sections. The sections reads all sections and the has_section checks if there is the specified section.
#!/usr/bin/python import configparser config = configparser.ConfigParser() config.read('db.ini') sections = config.sections() print(f'Sections: ') sections.append('sqlite') for section in sections: if config.has_section(section): print(f'Config file has section ') else: print(f'Config file does not have section ')
The example works with sections.
$ python sections.py Sections: ['mysql', 'postgresql'] Config file has section mysql Config file has section postgresql Config file does not have section sqlite
Python ConfigParser read from string
Since Python 3.2, we can read configuration data from a string with the read_string method.
#!/usr/bin/python import configparser cfg_data = ''' [mysql] host = localhost user = user7 passwd = s$cret db = ydb ''' config = configparser.ConfigParser() config.read_string(cfg_data) host = config['mysql']['host'] user = config['mysql']['user'] passwd = config['mysql']['passwd'] db = config['mysql']['db'] print(f'Host: ') print(f'User: ') print(f'Password: ') print(f'Database: ')
The example reads configuration from a string.
Python ConfigParser read from dictionary
Since Python 3.2, we can read configuration data from a dictionary with the read_dict method.
#!/usr/bin/python import configparser cfg_data = < 'mysql': > config = configparser.ConfigParser() config.read_dict(cfg_data) host = config['mysql']['host'] user = config['mysql']['user'] passwd = config['mysql']['passwd'] db = config['mysql']['db'] print(f'Host: ') print(f'User: ') print(f'Password: ') print(f'Database: ')
The example reads configuration from a Python dictionary.
Keys are section names, values are dictionaries with keys and values that are present in the section.
Python ConfigParser write
The write method writes configuration data.
#!/usr/bin/python import configparser config = configparser.ConfigParser() config.add_section('mysql') config['mysql']['host'] = 'localhost' config['mysql']['user'] = 'user7' config['mysql']['passwd'] = 's$cret' config['mysql']['db'] = 'ydb' with open('db3.ini', 'w') as configfile: config.write(configfile)
The example writes config data into the db3.ini file.
First, we add a section with add_section .
config['mysql']['host'] = 'localhost' config['mysql']['user'] = 'user7' config['mysql']['passwd'] = 's$cret' config['mysql']['db'] = 'ydb'
with open('db3.ini', 'w') as configfile: config.write(configfile)
Finally, we write the data with write .
Python ConfigParser interpolation
ConfigParser allows to use interpolation in the configuration file. It uses the % syntax.
[info] users_dir= C:\Users name= Jano home_dir= %(users_dir)s\%(name)s
We build the home_dir with interpolation. Note that the ‘s’ character is part of the syntax.
#!/usr/bin/python import configparser config = configparser.ConfigParser() config.read('cfg.ini') users_dir = config['info']['users_dir'] name = config['info']['name'] home_dir = config['info']['home_dir'] print(f'Users directory: ') print(f'Name: ') print(f'Home directory: ')
The example reads the values and prints them.
$ python interpolation.py Users directory: C:\Users Name: Jano Home directory: C:\Users\Jano
In this tutorial we have used ConfigParser to work with configuration data in Python.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.