user4792512
user4792512

Reputation: 23

configparser is dropping comments when writing out

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

Answers (1)

user2454725
user2454725

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

Related Questions