gpt4 book ai didi

python - 为 Python 程序创建配置文件

转载 作者:太空狗 更新时间:2023-10-29 21:03:10 24 4
gpt4 key购买 nike

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

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

我在 Windows 7 上使用 Python 3.4。

最佳答案

使用 ConfigParser 您走在正确的轨道上!链接的文档在使用它进行编程时应该非常有用。

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

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)

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

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

然后您就可以像使用任何其他词典一样简单地使用它。访问如下值:

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

归功于 python 文档。

关于python - 为 Python 程序创建配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29344196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com