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(非常建议),但以更简单的方式,只需添加:
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)
您可以扩展ConfigParser
类并覆盖write
这产生以下输出文件:
[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)