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.
config.add_section('ExampleSection')

# 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')  
config.write(f)  
f.close()

# Read from the file.
config.read('C:/config.ini')

# Print the sections stored in the config.
print(config._sections)

# Print the first option in the specified section.
print(config._sections['ExampleSection']['option1'])  

comments powered by Disqus