2

I have a cfg file. In that cfg file there is a line like:

[Environment]
automation_type=GFX   ;available options: GEM, HEXAII

I want to modify this line by:

[Environment]
automation_type=ABC   ;available options: GEM, HEXAII

I have written the below code for 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)
    for sec in config.sections():
        for attr in config.options(sec):
            if sec =='Environment' and attr == 'automation_type':
                config.set('Environment','automation_type','ABC')
    with open(get_path_for_OpenDebug_cfg, 'wb') as configfile:
        config.write(configfile)

After executing the code, I get

[Environment]
automation_type = ABC

";available options: GEM, HEXAII" this line is missing.
2
  • That line is a comment. I don't think RawConfigParser objects store comments. Commented Apr 25, 2013 at 13:20
  • 1
    this is because ";available options: GEM, HEXAII" is a comment. I think you should either move the comments to another line, or use simple text-processing techniques, instead of ConfigParser. Commented Apr 25, 2013 at 13:22

1 Answer 1

6

As the source code suggests, when reading config files, comments are ignored, both those on separate lines (484)...

if line.strip() == '' or line[0] in '#;':
     continue

and on option lines (522):

if vi in ('=', ':') and ';' in optval:
     # ';' is a comment delimiter only if it follows
     # a spacing character
     pos = optval.find(';')
     if pos != -1 and optval[pos-1].isspace():
         optval = optval[:pos]

So I agree with the comment above saying that you should switch to something more low-level if you care about preserving comments.

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

Comments

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.