My code
with open('config.ini', 'a+') as fp: # have tried r+ also, same result
config = ConfigParser()
config.read(fp) # have tried config.read_string(fp.read()) also
print(config.sections()) # this is [] every time somehow
if 'section' not in config:
config.add_section('section')
section = config['section']
section['option'] = 'value'
config.write(fp)
and the ini file, instead of getting overwritten, keeps on appending these same duplicate entries and I get no exception either. A Section being a dictionary should not have this type of behavior.
But when I separate read and writing code like this it works as expected:
config = ConfigParser()
config.read(fp)
with open('config.ini', 'w') as fp:
if 'section' not in config:
config.add_section('section')
section = config['section']
section['option'] = 'value'
config.write(fp)
I think this has something to do with the position of fp
.