- 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
- Basic configparser usage
- Notes on reading an INI file
- Writing an INI file
- Advanced configparser usage
- ExtendedInterpolation
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.
Basic configparser usage
These are some examples on using ConfigParser, assuming the following INI file.
[SectionOne] Status: Single Name: Derek Value: Yes Age: 30 Single: True [SectionTwo] FavoriteColor = Green [SectionThree] FamilyName: Johnson [Others] Route: 66
>>> import ConfigParser >>> Config = ConfigParser.ConfigParser() >>> Config >>> Config.read("c:\\tomorrow.ini") ['c:\\tomorrow.ini'] >>> Config.sections() ['Others', 'SectionThree', 'SectionOne', 'SectionTwo'] >>>
Explanation: We first import the configparser, tell it to read the file, and get a listing of the sections. Sections are listed in square brackets [].
Next, we are going to get some settings, after defining a helper function.
def ConfigSectionMap(section): dict1 = <> options = Config.options(section) for option in options: try: dict1[option] = Config.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1
>>> Name = ConfigSectionMap("SectionOne")['name'] >>> Age = ConfigSectionMap("SectionOne")['age'] >>> print "Hello %s. You are %s years old." % (Name, Age) Hello Derek. You are 30 years old.
This works great most of the time, but what about the «Value: Yes» and «Single: True» values? Those are booleans. They can be either True or False, Yes or No, 1 or 0, on or off. To read a boolean value, you use: Config.getboolean(section, option) Example, continuing from above:
>>> single = Config.getboolean("SectionOne", "single") >>> single True
You can also use getint(section, option) to get a number as an int. This may be easier to use than int(Config.get(section, option)) There is also getfloat which is used the same as getint, but, as you guessed, returns a float instead of an int.
Notes on reading an INI file
lines beginning with a semicolon ‘;’ a pound sign ‘#’ or the letters ‘REM’ (uppercase or lowercase) will be ignored. You may use these for comments if you want. You cannot put a comment on an option line. It will only be treated as a comment if it is at the beginning of the line!
Writing an INI file
When you write to an INI file, you will wipe out all comments.
Assuming the config file doesn’t exist yet, this is the code to create one:
# lets create that config file for next time. cfgfile = open("c:\\next.ini",'w') # add the settings to the structure of the file, and lets write it out. Config.add_section('Person') Config.set('Person','HasEyes',True) Config.set('Person','Age', 50) Config.write(cfgfile) cfgfile.close()
Advanced configparser usage
ExtendedInterpolation
Using ExtendedInterpolation one can make use of cross-chapter flexible parameter values. For instance, using the following ini file:
[SectionOne] Param1: Hello Param2: World [SectionTwo] Param1: $ $ [SectionThree] Alpha: One Bravo: Two Charlie: $ Mississippi
By setting _interpolation to ExtendedInterpolation() the values become dynamic.
>>> import configparser >>> settings = configparser.ConfigParser() >>> settings._interpolation = configparser.ExtendedInterpolation() >>> settings.read('settings.ini') ['settings.ini'] >>> settings.sections() ['SectionOne', 'SectionTwo', 'SectionThree'] >>> settings.get('SectionTwo', 'Param1') 'Hello World' >>> settings.get('SectionThree', 'Charlie') 'One Mississippi'
ConfigParserExamples (last edited 2016-04-11 04:17:05 by bignose )