How do I modify a configuration file using python? -
i have cfg file. in cfg file there line like:
[environment] automation_type=gfx ;available options: gem, hexaii
i want modify line by:
[environment] automation_type=abc ;available options: gem, hexaii
i have written below code this:
get_path_for_od_cfg = r"c:\users\marahama\desktop\abdur\abc_mainreleasefolder\od\od\odconfig.cfg" config = configparser.rawconfigparser() config.read(get_path_for_opendebug_cfg) sec in config.sections(): attr in config.options(sec): if sec =='environment' , attr == 'automation_type': config.set('environment','automation_type','abc') open(get_path_for_opendebug_cfg, 'wb') configfile: config.write(configfile)
after executing code, get
[environment] automation_type = abc
";available options: gem, hexaii" line missing.
as source code suggests, when reading config files, comments ignored, both on separate lines (484)...
if line.strip() == '' or line[0] in '#;': continue
and on option lines (522):
if vi in ('=', ':') , ';' in optval: # ';' comment delimiter if follows # spacing character pos = optval.find(';') if pos != -1 , optval[pos-1].isspace(): optval = optval[:pos]
so agree comment above saying should switch more low-level if care preserving comments.