Python ConfigParser With Examples

Python ConfigParser

Python ConfigParser module is an extremely important one when it comes to creating configurable applications.

To provide a quick summary, using configparser module, we can keep the configuration related to our application in a configuration file, anywhere in the system and access it inside our application.

So, if we suppose that we keep our database connection details in the config file, we just need to change them to make our application point to a completely new database. This means that we didn’t have to change anything in our application to do this!

What can config file include?

Thie config files we create can contain integers, floating point values, and Booleans. Specifically, here are important points:

Let’s look at a sample config file as well which will clear things well.

See, how easy was that! The values which can be used programmatically in above files are url, username and password.

Python Config Files

Let’s put these concepts into use with some code snippets.

Using config files

We will be creating a sample config file which looks like this:

Make this file and name it database.config and keep it in the same directory as the program we write next:

Here, we first find the section and then we continue to providing the exact key which we need. This is even good in terms of code readability. Let’s see the output for this program:

python configparser ifexists

This was pretty simple actually.

Checking if config file exist

Before using the key values in our program, it will always be better if we check if the config file exists at all. With this, we can integrate a much better error mechanism in our application and maybe, inform the user if config files are missing.

Let’s see the code snippet:

Let’s see the output for this program:

python-configparser-ifexists

Iterating over all values present

We can iterate over all the sections and values present in the config files to look for a particular value or do any other operations.

Let’s see the code snippet on how this can be done:

Let’s see the output for this program:

python-configparser-iteration

Checking if a section is present

Wouldn’t it be better if we could just provide a section key and check if the section is present or not? It is possible actually and that’s what we will do in next code snippet:

Let’s see the output for this program:

python-configparser-section-exists

Checking if a value is present

Now, let’s directly check if the value is present or not. Let’s see the code snippet on how this can be done:

Let’s see the output for this program:

python-configparser-section-ifexists

Conclusion

In this post, we saw how we can use Python‘s configparser module to access config files and put it to use in our application.

Reference: API Doc

By admin

Leave a Reply