Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7397863
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T03:48:04+00:00 2026-05-29T03:48:04+00:00

I have config file, [local] variable1 : val1 ;#comment1 variable2 : val2 ;#comment2 code

  • 0

I have config file,

[local]
    variable1 : val1 ;#comment1
    variable2 : val2 ;#comment2

code like this reads only value of the key:

class Config(object):
    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('config.py')

    def get_path(self):
        return self.config.get('local', 'variable1')

if __name__ == '__main__':
    c = Config()
    print c.get_path()

but i also want to read the comment present along with the value, any suggestions in this regards will be very helpful.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T03:48:04+00:00Added an answer on May 29, 2026 at 3:48 am

    Your only solutions is to write another ConfigParser overriding the method _read(). In your ConfigParser you should delete all checks about comment removal. This is a dangerous solution, but should work.

    class ValuesWithCommentsConfigParser(ConfigParser.ConfigParser):
    
        def _read(self, fp, fpname):
            from ConfigParser import DEFAULTSECT, MissingSectionHeaderError, ParsingError
    
            cursect = None                        # None, or a dictionary
            optname = None
            lineno = 0
            e = None                              # None, or an exception
            while True:
                line = fp.readline()
                if not line:
                    break
                lineno = lineno + 1
                # comment or blank line?
                if line.strip() == '' or line[0] in '#;':
                    continue
                if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
                    # no leading whitespace
                    continue
                    # continuation line?
                if line[0].isspace() and cursect is not None and optname:
                    value = line.strip()
                    if value:
                        cursect[optname].append(value)
                # a section header or option header?
                else:
                    # is it a section header?
                    mo = self.SECTCRE.match(line)
                    if mo:
                        sectname = mo.group('header')
                        if sectname in self._sections:
                            cursect = self._sections[sectname]
                        elif sectname == DEFAULTSECT:
                            cursect = self._defaults
                        else:
                            cursect = self._dict()
                            cursect['__name__'] = sectname
                            self._sections[sectname] = cursect
                            # So sections can't start with a continuation line
                        optname = None
                    # no section header in the file?
                    elif cursect is None:
                        raise MissingSectionHeaderError(fpname, lineno, line)
                    # an option line?
                    else:
                        mo = self._optcre.match(line)
                        if mo:
                            optname, vi, optval = mo.group('option', 'vi', 'value')
                            optname = self.optionxform(optname.rstrip())
                            # This check is fine because the OPTCRE cannot
                            # match if it would set optval to None
                            if optval is not None:
                                optval = optval.strip()
                                # allow empty values
                                if optval == '""':
                                    optval = ''
                                cursect[optname] = [optval]
                            else:
                                # valueless option handling
                                cursect[optname] = optval
                        else:
                            # a non-fatal parsing error occurred.  set up the
                            # exception but keep going. the exception will be
                            # raised at the end of the file and will contain a
                            # list of all bogus lines
                            if not e:
                                e = ParsingError(fpname)
                            e.append(lineno, repr(line))
                # if any parsing errors occurred, raise an exception
            if e:
                raise e
    
            # join the multi-line values collected while reading
            all_sections = [self._defaults]
            all_sections.extend(self._sections.values())
            for options in all_sections:
                for name, val in options.items():
                    if isinstance(val, list):
                        options[name] = '\n'.join(val)
    

    In the ValuesWithCommentsConfigParser I fixed some imports and deleted the appropriate sections of code.

    Using the same config.ini from my previous answer, I can prove the previous code is correct.

    config = ValuesWithCommentsConfigParser()
    config.read('config.ini')
    assert config.get('local', 'variable1') == 'value1 ; comment1'
    assert config.get('local', 'variable2') == 'value2 # comment2'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

hi this code works fine and my config file changes correctly. //Local Variable Declaration
I have a config file: in branch master : url=http://somewhere.com in branch local :
I have a setup like this. SVN Repository Live Site Dev Site Local Copy
I have a config file that I read using the RawConfigParser in the standard
I have referenced a config file that is located in a solution folder. I
I have an app.config file inside my TestProject, but when I try to read
I have a large config file (user) that i needed to go to the
As many do I have a config.php file in the root of a web
In a servlet I have a config text file. How to prevent web access
In my ASP.NET application I have a web.config file. In the web.config file I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.