Configuration Files in Python¶
- Quick Overview (Basic configuration file).
- How to make it.
- How to access them.
- How to update it.
- Real Example.
Quick Overview (Basic Configuration File)¶
- The Files consist of sections.
- Name of the section is withing
[]
, Example:[DEFAULT]
or[testing]
. - Each section will contain keys with values
- The extension of the file is
.ini
Supported structure¶
- Section names are case-sensitive
[Default]
is different than[default]
. - Spaces are allowed in the keys and the values,
my key = my value
=
or:
can be used to separate keys and values.- keys with no values can omit
=
or it can be used if is not followed by any character,my key without value
ormy key without value =
are correct. - Comments can be added with
#
or;
like# I am a comment
and; me too
. - A section can be indented.
How to make it¶
I can make a config file in two ways:
- Creating the file and saving it with a .ini extension.
- Creating the file programmatically.
Creating a file programmatically can be done using a code similar to this:
All the values stored
in the keys are strings, however,
there is one method I can use to get a boolean value for keys holding strings like yes
, no
'on'
,'off'
,'true'
,'false'
,'1'
,'0'
.
How to access them¶
ConfigParser class provides methods to interact with the configuration file.
read()
Allow me to read the .ini file
sections()
returns the section names present in the config file.
getboolean()
will return a Boolean value depending on the value store in the key, values most be 'yes'/'no'
, 'on'/'off
', 'true'/'false'
and '1'/'0'
.
Here are some examples of interactions with a config file.
Like the dictionaries I can provide a Fallback value, that is when the key doesn't I can create it and give it a value.
How to update it.¶
To update it I can use the following methods:
add_section()
to add a new section.
set(’my_section’,’my_new_key’,’my_new_value’)
To add a new key-value pair to an specific session.
Notice I need to “save the changes” by writing the configuration file one more time.