How to edit an INI file in Python 2.7
I am trying to edit an INI config file that already has the Sections and Options I need. However I need to update the values depending on a checkboxlist in wxPython. Currently everything is working :), but I feel like there is a better way. Here is part of the function snippet I'm using.
def read_or_write_file(self, file, section, passed_option = None,
value = None, read = True):
if read:
with open(file) as configfile:
config = ConfigParser.RawConfigParser()
config.readfp(configfile)
options = config.options(section)
for option in options:
file_settings[option] = config.get(section, option)
else:
with open(file, 'r+') as configfile:
config = ConfigParser.RawConfigParser()
config.readfp(configfile)
config.set(section, passed_option, value)
with open(file, 'r+') as configfile:
config.write(configfile)
This works exactly how I want it to, I tell it what I want to read or write and it works.
However the else:
part where I write to the file seems strange. I have to edit config
first then rewrite everything in the configfile
.
Is there a way to only rewrite the value I am changing?
This is my first question, so if I forgot to mention something let me know.
Also a points of information: - I have looked at all of the documentation or at least what I could find - This is similar but not exactly what I need How to read and write INI file with Python3?