Search code examples
pythonconfigparser

How to use % signs in configparser python?


I am writing a config.ini file for my python project. I want to mention the standard date format of a column.

Something like this

prod_db_end_date   = 2017-01-01
prod_db_end_date_format = %Y-%m-%d

But it interpolates something else and errors out. Could someone please let me know how to use this?

Error traceback - File "C:\ProgramData\Anaconda3\lib\configparser.py", line 443, in _interpolate_some
      "found: %r" % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%Y-%m-%d'

Solution

  • You have three options:

    • Disable interpolation, or pick a different interpolation handler. You can set the interpolation option to None to disable interpolation for the whole file:

      ConfigParse(interpolation=None)
      

      See the Interpolation of values section.

    • Access that specific value with interpolation disabled, setting raw=True for the ConfigParser.get() method:

      config.get('section', 'prod_db_end_date_format', raw=True)
      
    • Double the % characters to %%:

      prod_db_end_date_format = %%Y-%%m-%%d