ConfigObj:防止写入空节

2024-09-22 16:37:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用ConfigObj(5.0.6,在Python2.7和Python3.8上)来管理我的配置,但是当我使用configspec中仅显示的某些部分写入文件配置时,它们仅显示为空部分,这是不需要的。如果您能提出任何建议来纠正ConfigObj的这种行为,我将不胜感激

发生情况的最小示例:

from configobj import ConfigObj
from validate import Validator

spec = ["[Section]", "option = boolean(default=True)"]

config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
config.validate(Validator())
print(config)
print(config.write())

输出:

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False', '[Section]']

所需输出(写入时不应有空节):

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False']

编辑1:我使用write()实际写入文件,所以我不希望只处理返回的字符串列表


Tags: 文件fromimportconfigfalsetruesectionvalidate
1条回答
网友
1楼 · 发布于 2024-09-22 16:37:07

要将默认值放入输出配置文件,请将^{}传递给验证:

from configobj import ConfigObj
from validate import Validator

spec = ["[Section]", "option = boolean(default=True)"]

config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
# set copy = True            vvvvvvvvvvv
config.validate(Validator(), copy = True)
print(config)
print(config.write())

这将提供您想要的输出

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', 'option2 = False', '[Section]', 'option = True']

相关问题 更多 >