4

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"
1
  • Variable names in curly braces are only automatically expanded in f-string literals, which can only exist in your actual Python source code - not in data files. You would need to explicitly perform the variable expansion yourself - perhaps key3.format(today=today) or key3.format(**globals()). Commented Jul 9, 2024 at 21:50

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.