Search code examples
python-3.xconfigparser

Python: Configparser: Adding item to section deletes other items


I have the following files:

main.py:

import configparser


config = configparser.ConfigParser()
config.add_section('section 1')
config.set('section 1', 'item3', 'c')

with open('file.txt', 'w') as configFile:
    config.write(configFile)

file.txt:

[section 1]
item1 = a
item2 = b

When running main.py I want item3 = c to just be added to section 1 without deleting any of the other items, however it results in the following file.txt:

[section 1]
item3 = c

How do I fix this?


Solution

  • Before you add item3, try reading your existing file first! Otherwise, you're just creating a brand new configuration that will not contain the contents of the file. Also, I don't think you need to create the section, since it will be parsed when you read the existing file.

    config.read('file.txt')