Write and Read Configuration Files Using Python

Configuration files are important in the storing of persistent data on the local disk and its retrieval for later use.

The data could be in the form of an automated timestamp of last access or it could be user-entered information such as a name or personal user settings.

In order to easily achieve this in Python, ConfigParser is required to be used.

Below is a quick example of writing to and reading from a configuration file.

import ConfigParser
# Instantiates the ConfigParser object.
config = ConfigParser.ConfigParser()
# Add a Section to the config file.
# Set the options in the section.
config.set('ExampleSection', 'option1', '1')
config.set('ExampleSection', 'option2', '2')
config.set('ExampleSection', 'option3', '3')
# Write to a file.
# NOTE: The file will be overwritten or created if it does not exist.
f = open('C:/config.ini', 'w')
# Read from the file.
# Print the sections stored in the config.
# Print the first option in the specified section.

Share This

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>