Search code examples
pythonpython-3.xiniconfigparser

Modify parameter values of sections in INI files Python


I have a .ini file which I want to modify a particular section. So for example,

[Section1]
Param1: Hello
Param2: World

[Section2]
fontsize = 10

[Section3]
integers = 971 508 1076 561

I want to modify the integers in section 3 and replace them with other integers. I have tried:

lis = "971 508 1076 561; 920 543 973 648 ; 831 492 936 544 ; 936 403 988 508"
config.set('sfr',lis)

But I'm getting errors; how can I fix this?

import configparser
config = configparser.ConfigParser()
config.read("C:\\Users\\Folder\\example.ini")
print(config.sections())
lis = "971 508 1076 561; 920 543 973 648 ; 831 492 936 544 ; 936 403 988 508"
config.set('sfr',lis)

Solution

  • You're missing the section and field to change the values of, try with:

    config.set("Section3", "integers", lis)
    

    Keep in mind that after changing the values you still need to save your config:

    with open("C:\\Users\\Folder\\example.ini", "w") as f:
        config.write(f)