Creating a config file

2019-06-17 03:58发布

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.

标签: python config
1条回答
祖国的老花朵
2楼-- · 2019-06-17 05:00

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.

查看更多
登录 后发表回答