Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a config file for Python Program

Tags:

python

config

I have created a small Python GUI for controlling the I2C pins of my MCU board. Now I want to try and save the settings of this GUI into a config file, so that the file settings could be changed based on the MCU being used.

I have no idea how to create a config file. I tried to looking into links on how to create and use a config file (e.g. ConfigParse), but could not understand much. Can somebody please help me out?

I am using Python 3.4 on Windows 7.

like image 919
Goldengirl Avatar asked Mar 30 '15 10:03

Goldengirl


People also ask

What is config in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.

How do I open a config file in Python?

Just put the abc.py into the same directory as your script, or the directory where you open the interactive shell, and do import abc or from abc import * .


1 Answers

You're on the right tracks with using ConfigParser! Linked are the docs that should be very useful when programming using it.

For you, the most useful think will likely be the examples, which can be found here. A simple program to write a config file can be found below

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
  config.write(configfile)

This program will write some information to the file "example.ini". A program to read this:

import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections()) #Prints ['bitbucket.org', 'topsecret.server.com']

Then you can simply use it like you would any other dictionary. Accessing values like:

config['DEFAULT']['Compression'] #Prints 'yes'

Credit given to python docs.

like image 145
Alexander Craggs Avatar answered Sep 27 '22 18:09

Alexander Craggs