I want to update a particular variable of an existing section of the config file in :Python. The config file looks like this:
[my_section]
var1 = 1
var2 = 2
var3 = 3
I am able to read the variables of the existing section (my_section). I want to update either of the variables var1, var2, var3. The code for reading and writing is given below, but the existing code overwrites the entire config file.
import configparser
def read_configs():
configs = configparser.ConfigParser()
configs.read("configs.ini")
x=configs.get("osdp_configs","var1")
y=configs.get("osdp_configs","var2")
z=configs.get("osdp_configs","var3")
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
print(configs.sections())
def write_configs():
configs = configparser.ConfigParser()
configs.add_section("osdp_configs")
configs.set("osdp_configs","var1","123")
configs.set("osdp_configs","var2","456")
with open("configs.ini","w") as h:
configs.write(h)
read_configs()
write_configs()
read_configs()
The write function write_configs overwrites in entire config file
How can I fix this issue?
configs.read("configs.ini")before you add sections and overwrite the file