创建配置文件

Gol*_*irl 8 python config

我已经创建了一个小的Python GUI来控制我的MCU板的I2C引脚.现在我想尝试将此GUI的设置保存到配置文件中,以便可以根据所使用的MCU更改文件设置.

我不知道如何创建配置文件.我试图查看有关如何创建和使用配置文件的链接(例如ConfigParse),但无法理解.有人可以帮帮我吗?

我在Windows 7上使用Python 3.4.

Ale*_*ggs 6

使用ConfigParser可以助您一臂之力!链接的文档在使用它进行编程时应该会非常有用。

对您来说,最有用的想法可能是示例,可以在此处找到。可以在下面找到编写配置文件的简单程序

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)
Run Code Online (Sandbox Code Playgroud)

该程序会将一些信息写入文件“ example.ini”。读取此程序:

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

然后,您可以像使用其他任何词典一样简单地使用它。访问类似的值:

config['DEFAULT']['Compression'] #Prints 'yes'
Run Code Online (Sandbox Code Playgroud)

归功于python docs。