Question

Create config file for python script with variables

I have a config file for a python script that stores multiple different values

my config.ini looks like this:

[DHR]
key1 = "\\path1\..."
key2 = "\\path2\..."
key3 = "\\path3\file-{today}.xlsx"

my .py has a date variable that gets today's date like:

today = str(date.today().strftime('%y%m%d'))

However when I read the .ini file the variable does not get appended to the value as I expected.

print(config.read("config.ini"))

"\\path3\file-{today}.xlsx"

How can I adjust my script to append the variable to the path so that it looks like this:

"\\path3\file-240709.xlsx"
 4  71  4
1 Jan 1970

Solution

 1

You could provide a filtered locals() dictionary to the parser to interpolate variables. However, the syntax of the ini needs to be changed to configparser's basic interpolation syntax:

[DHR]
key3 = "\\path3\file-%(today)s.xlsx"
from configparser import ConfigParser
from datetime import date

today = str(date.today().strftime('%y%m%d'))

# instantiate parser with local variables, filtered for string-only values
parser = ConfigParser({k: v for k, v in locals().items() if isinstance(v, str)})
parser.read('config.ini')

print(parser["DHR"]["key3"])  # => "\\path3\file-240710.xlsx"
2024-07-10
Christian Karcher

Solution

 0

As in some of the answers here, you can create your own custom interpolator class, e.g.,

import configparser

from datetime import date

today = str(date.today().strftime('%y%m%d'))

class DictInterpolation(configparser.BasicInterpolation):
    def __init__(self, dv: dict):
        super().__init__()

        self.dict = dv

    def before_get(self, parser, section, option, value, defaults):
        value = super().before_get(parser, section, option, value, defaults)
        return value.format(**self.dict)
    

interpolator = DictInterpolation({"today": today})

config = configparser.ConfigParser(interpolation=interpolator)

config.read("config.ini")

print(config["DHR"]["key3"])
"\\path3\file-240710.xlsx"

The custom DictInterpolator takes in a dictionary of substitutions and when parsing the values uses the string format method to substitute in any values held between {} that are given in the dictionary that you supply.

2024-07-10
Matt Pitkin