【发布时间】:2017-07-26 04:22:07
【问题描述】:
使用Python 2.7.x和ConfigParser,如何生成配置文件如下?
[Section]
key1
key2
key3
【问题讨论】:
标签: python-2.7 config delimiter ini
使用Python 2.7.x和ConfigParser,如何生成配置文件如下?
[Section]
key1
key2
key3
【问题讨论】:
标签: python-2.7 config delimiter ini
= 是格式的一部分,因此您不能告诉 configparser 忽略它。
但是您可以通过传递io.BytesIO() 对象来欺骗作者,并在写入真实文件时去掉空格+等号。
独立示例:
import ConfigParser,io
config = ConfigParser.RawConfigParser()
config.add_section('Section')
for i in range(1,4):
config.set('Section', 'key{}'.format(i), '')
# Writing our configuration file to 'example.cfg'
b = io.BytesIO()
config.write(b) # write in a fake file
# now write the modified contents to a real file
with open('output.ini', 'w') as f:
for l in b.getvalue().splitlines():
f.write(l.rstrip("= ")+"\n")
【讨论】:
请参阅 python 文档。 https://docs.python.org/2/library/configparser.html
import ConfigParser
config = ConfigParser.RawConfigParser()
config.add_section('Section')
config.set('Section', 'key1', '')
config.set('Section', 'key2', '')
config.set('Section', 'key3', '')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
【讨论】:
[Section] key1 = key2 = key3 = 无论如何要从中剥离 =