Python 2.7 不带分隔符的Python 2.7 ConfigParser

Python 2.7 不带分隔符的Python 2.7 ConfigParser,python-2.7,config,delimiter,ini,Python 2.7,Config,Delimiter,Ini,使用Python2.7.x和ConfigParser,如何生成如下配置文件 [Section] key1 key2 key3 请参阅python文档。 =是格式的一部分,因此您不能告诉configparser忽略它 但是您可以通过传递一个io.BytesIO()对象来愚弄编写器,并在写入真实文件时去掉空格+等号 独立示例: import ConfigParser,io config = ConfigParser.RawConfigParser() config.add_section('

使用Python2.7.x和ConfigParser,如何生成如下配置文件

[Section]
key1
key2
key3

请参阅python文档。


=
是格式的一部分,因此您不能告诉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")

它生成以下输出
[Section]key1=key2=key3=
是否仍有要从中剥离的内容
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")