配置类中的Python新部分
我正在尝试编写一个动态配置.ini 在这里,我可以添加带有键和值的新部分,也可以添加无键值。 我已经写了一段代码,创建了一个.ini。但这一部分是“默认”的。 此外,它只是在每次不添加新节的情况下覆盖文件 我已经用Python3编写了一段代码来创建一个.ini文件配置类中的Python新部分,python,Python,我正在尝试编写一个动态配置.ini 在这里,我可以添加带有键和值的新部分,也可以添加无键值。 我已经写了一段代码,创建了一个.ini。但这一部分是“默认”的。 此外,它只是在每次不添加新节的情况下覆盖文件 我已经用Python3编写了一段代码来创建一个.ini文件 import configparser """Generates the configuration file with the config class. The file is a .ini file""" class
import configparser
"""Generates the configuration file with the config class.
The file is a .ini file"""
class Config:
"""Class for data in uuids.ini file management"""
def __init__(self):
self.config = configparser.ConfigParser()
self.config_file = "conf.ini"
# self.config.read(self.config_file)
def wrt(self, config_name={}):
condict = {
"test": "testval",
'test1': 'testval1',
'test2': 'testval2'
}
for name, val in condict.items():
self.config.set(config_name, name, val)
#self.config.read(self.config_file)
with open(self.config_file, 'w+') as out:
self.config.write(out)
if __name__ == "__main__":
Config().wrt()
我应该能够添加新的部分与关键或没有关键。
附加键或值。
它应该有正确的节名。您的代码有一些问题:
- 使用可变对象作为默认参数可能有点困难 狡猾的,你可能会看到意想不到的行为
- 您正在使用传统的config.set()李>
- 您正在将配置名称默认为字典,为什么李>
- 空白太多:p
- 您不需要通过迭代字典项来使用更新的(非遗留)函数编写它们,如下所示
"""Generates the configuration file with the config class.
The file is a .ini file
"""
import configparser
import re
class Config:
"""Class for data in uuids.ini file management."""
def __init__(self):
self.config = configparser.ConfigParser()
self.config_file = "conf.ini"
# self.config.read(self.config_file)
def wrt(self, config_name='DEFAULT', condict=None):
if condict is None:
self.config.add_section(config_name)
return
self.config[config_name] = condict
with open(self.config_file, 'w') as out:
self.config.write(out)
# after writing to file check if keys have no value in the ini file (e.g: key0 = )
# the last character is '=', let us strip it off to only have the key
with open(self.config_file) as out:
ini_data = out.read()
with open(self.config_file, 'w') as out:
new_data = re.sub(r'^(.*?)=\s+$', r'\1', ini_data, 0, re.M)
out.write(new_data)
out.write('\n')
condict = {"test": "testval", 'test1': 'testval1', 'test2': 'testval2'}
c = Config()
c.wrt('my section', condict)
c.wrt('EMPTY')
c.wrt(condict={'key': 'val'})
c.wrt(config_name='NO_VALUE_SECTION', condict={'key0': '', 'key1': ''})
这将产生:
[DEFAULT]
key = val
[my section]
test = testval
test1 = testval1
test2 = testval2
[EMPTY]
[NO_VALUE_SECTION]
key1
key0
谢谢!这是有效的。现在字典的结构是dict{“key”:“value”}但是我还需要添加一些条目,比如dict{“test”、“test2”、“test3”},这给了我错误,比如“set”对象没有属性“items”。我添加了self.config=configparser.configparser(allow\u no\u value=True),但这也没有帮助。我还可以从python控制台更改此配置文件以添加新项或更改它吗?我认为ConfigParser不支持编写没有值的键。它确实支持读取没有值的ini文件(这就是allow_no_值的作用)。我已经更新了我的答案以手动处理此案例。我还进一步简化了代码(因为我不熟悉configParser库)。