Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

What are configuration files in Python?

Configuration files popularly called config files are special files that store some specific data and
settings for computer programs. Most computer programs read their configuration files at startup
and periodically check for changes in these configuration files.

The files can be used by the user to change the settings of the application without the need to
recompile the programs. Generally each configuration file consists of different sections. Each
section contains key and value pairs like a Python dictionary.

Given below is a sample configuration file which consists of three sections namely Address,
Education, and the Hobbies of a person. 

[Address]
Name = Aditya Raj
Village = Bhojpur
District = Samastipur
State = Bihar
 
[Education]
College=IIITA
Branch= IT
 
[Favorites]
Sport = VolleyBall
Book = Historical Books

Now we will create the above configuration file using the ConfigParser module in python.

How to create a configuration file using the Python


ConfigParser module?
To create a configuration file in python, we will use the configparser module. In the following
implementation, we create a ConfigParser object and add sections to it which are basically
dictionaries containing key-value pairs. Then we save the configuration file with the .ini
extension.

#import module
import configparser
 
#create configparser object
config_file = configparser.ConfigParser()
 
#define sections and their key and value pairs
config_file["Address"]={
        "Name": "Aditya Raj",
        "Village": "Bhojpur",
        "District": "Samastipur",
        "State": "Bihar"
        }
config_file["Education"]={
        "College":"IIITA",
        "Branch" : "IT"
        }
config_file["Favorites"]={
        "Sports": "VolleyBall",
        "Books": "Historical Books"
        }
 
#SAVE CONFIG FILE
with open("person.ini","w") as file_object:
    config_file.write(file_object)
print("Config file 'person.ini' created")
 
#print file content
read_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)

Output for above code snippet is:

Config file 'person.ini' created


content of the config file is:
[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books

How to add a new section in config files created with


ConfigParser?
To add new section in a config file, we can just read a config file in config object, add the new
section by defining the section in dictionary format and then we can save the config object into
the same file.

Here in the example below, we will add a new section “Physique” in the person.ini file which
already contains the Address, Education and Favorites sections.

import configparser
 
#print initial file content
read_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
 
#create new config object
config_object= configparser.ConfigParser()
 
#read config file into object
config_object.read("person.ini")
 
#Add new section named Physique
config_object["Physique"]={
        "Height": "183 CM",
        "Weight": "70 Kg"
        }
 
#save the config object back to file
with open("person.ini","w") as file_object:
    config_object.write(file_object)
 
#print the new config file
print("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)

Output for above code snippet is:

content of the config file is:


[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
 
Config file 'person.ini' updated
Updated file content is:
[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
[Physique]
height = 183 CM
weight = 70 Kg

We can also use add_section() method to add a new section and then use set() method to add
new fields in the section.

import configparser
 
#print initial file content
read_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
 
#create new config object
config_object= configparser.ConfigParser()
 
#read config file into object
config_object.read("person.ini")
 
#Add new section named Physique
config_object.add_section('Physique')
config_object.set('Physique', 'Height', '183 CM')
config_object.set('Physique', 'Weight', '70 Kg')
 
#save the config object back to file
with open("person.ini","w") as file_object:
    config_object.write(file_object)
 
#print the updated config file
print("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)

Output:

content of the config file is:


[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
 
Config file 'person.ini' updated
Updated file content is:
[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
[Physique]
height = 183 CM
weight = 70 Kg

In the above example, we can see that add_section() method takes section name as it’s
argument while set() method takes section name as it’s first argument,field name as it’s second
argument and value for field as it’s third argument.

These two methods can also be used while making a new config file to add sections and
fields to the file instead of using dictionaries as we have done in this example.

How to update data in configuration files?


As we have defined sections of the config files as dictionaries, the operations applicable on
dictionaries are also applicable on sections of config files. We can add fields in any section of
config file or modify the value of the field in a similar manner as we do with dictionary items.

In the following code we have added a new field “Year” in “Education” section of person.ini
config file and modified the value of “Branch” field in the file.

import configparser
 
#print initial file content
read_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
 
#create new config object
config_object= configparser.ConfigParser()
 
#read config file into object
config_object.read("person.ini")
 
#update value of a field in a section
config_object["Education"]["Branch"]="MBA"
 
#add a new field in a section
config_object["Education"].update({"Year":"Final"})
 
#save the config object back to file
with open("person.ini","w") as file_object:
    config_object.write(file_object)
 
#print updated content
print("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)

Output:

content of the config file is:


[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = IT
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
[Physique]
height = 183 CM
weight = 70 Kg
 
 
Config file 'person.ini' updated
Updated file content is:
[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = MBA
year = Final
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
[Physique]
height = 183 CM
weight = 70 Kg

In the above example, we can use update() method to add new fields as well as modify existing
fields. If the field given as argument exists in the file, it updates the field otherwise a new field is
created.

How to delete data from config file?


We can delete data from config files using remove_option() and remove_section() module in
configparser module. remove_option() is used to delete a field from any section and
remove_section() is used to delete a complete section of the config file.

import configparser
 
#print initial file content
read_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
 
#create new config object
config_object= configparser.ConfigParser()
 
#read config file into object
config_object.read("person.ini")
 
#delete a field in a section
config_object.remove_option('Education', 'Year')
 
#delete a section
config_object.remove_section('Physique')
 
#save the config object back to file
with open("person.ini","w") as file_object:
    config_object.write(file_object)
 
#print new config file
print("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)

Output:

content of the config file is:


[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = MBA
year = Final
 
[Favorites]
sports = VolleyBall
books = Historical Books
 
[Physique]
height = 183 CM
weight = 70 Kg
 
 
Config file 'person.ini' updated
Updated file content is:
[Address]
name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
 
[Education]
college = IIITA
branch = MBA
 
[Favorites]
sports = VolleyBall
books = Historical Books

In the above example, we can see that remove_option() method takes section name as it’s first
argument and field name as it’s the second argument whereas remove_section() method takes
the name of the section to be deleted as its argument.

You might also like