在我的Python程序中,我读取了一个配置(在我的实际代码中来自文件),但在写入时,注释消失了。我怎么能把它留在那里?
import sys
import ConfigParser
import io
sample_config = """
[user01]
name = Sal
# update this value
password = abc123
"""
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))
config.set('user01', 'password', '123abc')
config.write(sys.stdout)
输出:
[user01]
name = Sal
password = 123abc
答案 0 :(得分:1)
我使用configobj,因为它在您读写时会保留注释 配置文件:
from configobj import ConfigObj
sample_config = """
[user01]
name = Sal
# update this value
password = abc123
"""
config = ConfigObj(sample_config.splitlines())
config['user01']['password'] = '123abc'
config.write(sys.stdout)