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 = [Link]()
font = "Courier"
font_size = 8
config.add_section("Settings")
[Link]("Settings", "font", "{font}".format(font=font))
[Link]("Settings", "font_size", "10")
[Link]("Settings", "font_style", "Normal")
[Link]("Settings", "font_info",
"You are using %(font)s at %(font_size)s pt".format(
font=font, font_size=font_size))
with open(path, "w") as config_file:
[Link](config_file)
if __name__ == "__main__":
path = "[Link]"
createConfig(path)
The code above will create a config file with one section labelled Settings that
will contain four options: font, font_size, font_style and font_info. Also note
that in Python 3 we only need to specify that we’re writing the file in write-
only mode, i.e. “w”. Back in Python 2, we had to use “wb” to write in binary
mode.