1

I have a question regarding adding variable value to text that is read from file. My situation is that I would like to have separate html file with variables that would pull value from code.

Example of .txt file:

"""Current value of variable x is: """ + str(x) + """ and so on."""

Code that I have tried, is:

x = 5
f = open("C:\\Test\\reading.txt",'r')
print(f.read())

What I would like to finish with is:

"""Current value of variable x is: 5 and so on."""

Reason why I would like to have it is to have separate html file, generate html code from it in combination with variable values and than use that string further for sending email. Worst case, I can embed html code into code where I calculate variable values, but would be more handy to keep them separated.

2
  • 1
    Sounds vaguely like you are looking for HTML templates. A common simple template engine is jinja which is used e.g. in flask. Commented Jan 31, 2018 at 11:15
  • What you are looking for is template engine. see: fullstackpython.com/template-engines.html Commented Jan 31, 2018 at 11:17

1 Answer 1

1

As pointed by @tripleee, package jinja2 is what you're looking for.

Inside your template.html file, you can just add spots for variables e.g.

<p>Current value of variable x is: {{ my_variable }} and so on.</p>

And render them using .render() from jinja.

import jinja2
template_loader = jinja2.FileSystemLoader(searchpath="./")
template_env = jinja2.Environment(loader=template_loader)
template_file = "./template.html"
template = template_env.get_template(template_file)
my_variable = 2
output_text = template.render(my_variable=my_variable) # this is where to put args to the template renderer
with open('./output.html', 'w') as f:
    f.write(output_text)

And now your file output.html is

<p>Current value of variable x is: 2 and so on.</p>
Sign up to request clarification or add additional context in comments.

3 Comments

Cheers, that did the trick. Thank you very much for fast response.
Would just like to point out one thing regarding template - at least in my case, it did not work with 3 {} for variable placeholder, 2 {} did the trick.
Absolutely, I can find only {{ in my templates. Or {% for chained placeholders. You're right, I'll edit that. Thanks :)

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.