Sunday, April 3, 2011

Python - ConfigParser throwing comments

Hi,

Based on ConfigParser module how can I filter out and throw every comments from an ini file?

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")

for section in config.sections():
    print section
    for option in config.options(section):
        print option, "=", config.get(section, option)

eg. in the ini file below the above basic script prints out the further comments lines as well like:

something  = 128     ; comment line1
                      ; further comments 
                       ; one more line comment

What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers

From stackoverflow
  • according to docs lines starting with ; or # will be ignored. it doesn't seem like your format satisfies that requirement. can you by any chance change format of your input file?

    edit: since you cannot modify your input files, I'd suggest pre-parsing them with something along the lines:

    tmp_fname = 'config.tmp'
    with open(config_file) as old_file:
        with open(tmp_fname, 'w') as tmp_file:
            tmp_file.writelines(i.replace(';', '\n;') for i in old_lines.readlines())
    # then use tmp_fname with ConfigParser
    

    obviously if semi-colon is present in options you'll have to be more creative.

  • It seems your comments are not on lines that start with the comment leader. It should work if the comment leader is the first character on the line.

    sykora : Then you'll probably have to create a temporary file and/or use ConfigParser.readfp() to scrap the comments.
  • Best way is to write a commentless file subclass:

    class CommentlessFile(file):
        def readline(self):
            line = super(CommentlessFile, self).readline()
            if line:
                line = line.split(';', 1)[0].strip()
                return line + '\n'
            else:
                return ''
    

    You could use it then with configparser (your code):

    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.readfp(CommentlessFile("sample.cfg"))
    
    for section in config.sections():
        print section
        for option in config.options(section):
            print option, "=", config.get(section, option)
    
    sykora : I think there's a small typo there, it should be super(CommentlessFile, self).readline(), instead of CommentRemover.
    nosklo : @sykora: I fixed that 5 seconds after the first post :)

0 comments:

Post a Comment