没有空格周围的操作员configparser

问题描述 投票:0回答:2
this脚本:

import ConfigParser config = ConfigParser.ConfigParser() config.optionxform = str with open('config.ini', 'w') as config_file: config.add_section('config') config.set('config', 'NumberOfEntries', 10) config.write(config_file)
生产:

[config] NumberOfEntries = 10
there
key

property
不是由“ =”界定的,而是“ =”(相等的符号被空间包围)。
如何指示python,使用“ =”作为configparser的定界符?
    

您可以只使用configparser(非常建议),但以更简单的方式,只需添加:

python config
2个回答
21
投票
with open('example.ini', 'w') as configfile: ... config.write(configfile, space_around_delimiters=False)

如下所述:

https://docs.python.org/3/library/configparser.html#configparser.configparser.write



write(fileobject, space_around_delimiters=True)

将配置表示为指定的文件对象的表示,该对象必须在文本模式(接受字符串)中打开。可以通过将来的读取()调用来解析此表示形式。如果space_around_delimiter是真实的,则密钥和值之间的定界符被空间包围。

您可以扩展
ConfigParser
类并覆盖

write

方法,以使其行为自己想要的方式。

1
投票

这产生以下输出文件:

[config]
NumberOfEntries=10
    

thumething类似于@Rchang写的内容;您可以使用super
的witr()方法的默认值覆盖默认值
import configparser class CustomConfigParser(configparser.ConfigParser): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def write(self, fp, space_around_delimiters = False): return super().write(fp, space_around_delimiters)


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.