0

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.

demberto
  • 489
  • 5
  • 15
  • 1
    It has nothing to do with the file pointer, But the file mode matters(`"a+"` only append the contents). If you want to overwrite use `w` instead. – Abdul Niyas P M Oct 01 '21 at 11:59
  • 1
    Basically you can ask the same question for `json` module/files. If you don't want to append, don't use mode `a` – buran Oct 01 '21 at 12:00
  • @buran I did want to append that's why I used `a+` or `r+`, since the config file is desktop.ini and might contain data I should not touch, however the code below works so its fine – demberto Oct 01 '21 at 12:03
  • mode `a+` (append) has a specific meaning in the context of file operations. If you think in the terms of dict (ConfigParser is in its essence a mapping) then you perform an update :-) Check https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function – buran Oct 01 '21 at 12:07
  • Does this answer your question? [Difference between modes a, a+, w, w+, and r+ in built-in open function?](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function) – buran Oct 01 '21 at 12:08
  • @buran Infact I thought about trying `a+` or `r+` after reading a similar [answer](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function/30566011#30566011). I can understand `a+` not working but what about `r+`? – demberto Oct 01 '21 at 12:15
  • 1
    `r+` mode works just fine. With your code - you open the file in `r+` mode, the stream is positioned at the beginning. You read the file (stream is at the end), You write - it appends at the end. If you want to reposition the stream at the beginning use `fp.seek(0)` just before write operation. Note, this may lead to very unexpected results - e.g. only partially overwrite data. So don't use it for this usecase – buran Oct 01 '21 at 12:32

0 Answers0