4

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)))
elethan
  • 16,408
  • 8
  • 64
  • 87
Alexandru Antochi
  • 1,295
  • 3
  • 18
  • 42

1 Answers1

8

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=';')
elethan
  • 16,408
  • 8
  • 64
  • 87