0

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?

1
  • You should probably call configs.read("configs.ini") before you add sections and overwrite the file Commented Nov 6, 2018 at 18:03

1 Answer 1

1

Open your configs.ini file in mode "append"

with open("configs.ini","a") as h:
  configs.write(h)

"write" mode replace all your content

Sign up to request clarification or add additional context in comments.

1 Comment

The append mode "a" again forms a seperate "my section".It dosen't update the variables of the existing section

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.