Reputation: 23
In my Python program, I read a config (in my real code from file), but on writing the comment is gone. How can I keep that in there?
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)
Output:
[user01]
name = Sal
password = 123abc
Upvotes: 2
Views: 121
Reputation:
I use configobj for that it preserves comments when you read and write the config files:
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)
Upvotes: 1