Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 ConfigParser reading the inline comments as well

I have the following code, where the filePath is the path to a cfg file on disk. When I parse it, it also reads the inline comments (the ones with space + ";").

Some lines of the result:

xlsx:Yes ; comment goes here

html:Yes ; comment goes here

It should be:

xlsx:Yes

html:Yes

def ParseFile(filePath):
    """this function returns the parsed CFG file"""
    parser = configparser.ConfigParser()
    print("Reading config file from %s" % filePath)
    parser.read(filePath)
    for section in parser.sections():
        print("[ SECTION: %s ]" % section)
        for option in parser.options(section):
            print("%s:%s" % (option, parser.get(section, option)))
like image 970
Alexandru Antochi Avatar asked Oct 23 '25 13:10

Alexandru Antochi


1 Answers

Inline comments are not enabled by default.

From an example in the docs:

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

To allow inline comments with ';':

parser = configparser.ConfigParser(inline_comment_prefixes=';')
like image 198
elethan Avatar answered Oct 26 '25 09:10

elethan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!