Configuration files are used by both users and programmers. They are usually used for storing your applications settings or even your operating system’s settings. Python’s core library includes a module called ConfigParser that you can use for creating and interacting with configuration files. We’ll spend a few minutes learning how it works in this article.

Creating a Config File

Creating a config file with ConfigParser is extremely simple. Let’s create some code to demonstrate:

import ConfigParser
 
#----------------------------------------------------------------------
def createConfig(path):
    """
    Create a config file
    """
    config = ConfigParser.ConfigParser()
    config.add_section("Settings")
    config.set("Settings", "font", "Courier")
    config.set("Settings", "font_size", "10")
    config.set("Settings", "font_style", "Normal")
    config.set("Settings", "font_info",
               "You are using %(font)s at %(font_size)s pt")
 
    with open(path, "wb") as config_file:
        config.write(config_file)
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    path = "settings.ini"
    createConfig(path)

The code above will create a config file with one section labeled Settings that will contain four options: font, font_size, font_style and font_info. Also note that when we write the config to disk, we use the “wb” flag to write in binary mode. This is not required, but it’s how the official documentation example does it. You can use the normal “w” flag as well and it will still work. I haven’t been able to find anything in the documentation that gives a reason for one over the other.

How to Read, Update and Delete Options

Now we’re reading to learn how to read the config file, update its options and even how to delete options. In this case, it’s easier to learn by actually writing some code! Just add the following function to the code that you wrote above.

import ConfigParser
 
#----------------------------------------------------------------------
def crudConfig(path):
    """
    Create, read, update, delete config
    """
    if not os.path.exists(path):
        createConfig(path)
 
    config = ConfigParser.ConfigParser()
    config.read(path)
 
    # read some values from the config
    font = config.get("Settings", "font")
    font_size = config.get("Settings", "font_size")
 
    # change a value in the config
    config.set("Settings", "font_size", "12")
 
    # delete a value from the config
    config.remove_option("Settings", "font_style")
 
    # write changes back to the config file
    with open(path, "wb") as config_file:
        config.write(config_file)
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    path = "settings.ini"
    crudConfig(path)

This code first checks to see if the path for the config file exists. If it does not, then it uses the createConfig function we created earlier to create it. Next we create a ConfigParser object and pass it the config file path to read. To read an option in your config file, we call the our ConfigParser object’s get method, passing it the section name and the option name. This will return the option’s value. If you want to change an option’s value, then you use the set method, where you pass the section name, the option name and the new value. Finally, you can use the remove_option method to remove an option.

In our example code, we change the value of font_size to “12” and we remove the font_style option completely. Then we write the changes back out to disk.

How to Use Interpolation

The ConfigParser module also allows interpolation, which means you can actually use some options to build another option. We actually do this with the font_info option in that its value is based on the font and font_size options. We can actually change an interpolated value using a Python dictionary. Let’s take a moment to demonstrate both of these facts.

import ConfigParser
 
#----------------------------------------------------------------------
def interpolationDemo(path):
    """"""
    if not os.path.exists(path):
        createConfig(path)
 
    config = ConfigParser.ConfigParser()
    config.read(path)
 
    print config.get("Settings", "font_info")
 
    print config.get("Settings", "font_info", 0,
                     {"font": "Arial", "font_size": "100"})
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    path = "settings.ini"
    interpolationDemo(path)

If you run this code, you should see output similar to the following:

You are using Courier at 12 pt
You are using Arial at 100 pt

Wrapping Up

At this point, you should know enough about the ConfigParser’s capabilities that you can use it for your own projects. There’s another project called ConfigObj that isn’t a part of Python that you might also want to check out. ConfigObj is more flexible and has more features than ConfigParser. But if you’re in a pinch or your organization doesn’t allow 3rd party packages, then ConfigParser will probably fit the bill.

Additional Reading

Print Friendly