1
votes

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

5
What does "throw out" mean? Please provide a clear statement of what you're really trying to do -- why do you need to "throw out" data from a file? Where does it go? What's left behind? - S.Lott

5 Answers

5
votes

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.

3
votes

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)
2
votes

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.

1
votes

As the doc said: "(For backwards compatibility, only ; starts an inline comment, while # does not.)" So use ";" and not "#" for inline comments. It is working well for me.

0
votes

Python 3 comes with a build-in solution: The class configparser.RawConfigParser has constructor argument inline_comment_prefixes. Example:

class MyConfigParser(configparser.RawConfigParser):
    def __init__(self):
      configparser.RawConfigParser.__init__(self, inline_comment_prefixes=('#', ';'))