Skip to content Skip to sidebar Skip to footer

Python: Placeholder Variables In Text File

I have a text file called help.txt which will be read and the contents printed out. I need the file to contain variable placeholders where the variable value will be substituted in

Solution 1:

If I understood you correctly you could just check the file as you read it in for these placeholders and replace them with your variable. Given 'FileContents' is the string you used to read in your file and 'variable' is the variable to replace it with, just use FileContents.replace("{one}", variable)

Solution 2:

f-strings are effectively syntactic sugar for str.format with some fancy processing of the namespaces. You can achieve the same effect using str.format on the contents of the file. The advantage of doing that over str.replace is that you have access to the full power of the string formatting mini-language.

I would recommend storing all the legal replacements into a dictionary rather than attempting to use globals or locals. This is not only safer, but easier to maintain, since you can easily load the variables from a file that way:

variables = {
    'one': 1,
    'two': 'b',
    'three': ...,
}

Printing the file is now trivial:

withopen('help.txt') as f:
    for line in f:
        print(line.format(**variables), end= '')

Post a Comment for "Python: Placeholder Variables In Text File"