Lucian Blaga
Lucian Blaga

Reputation: 147

How to use a text file as a template?

I want to load a text file and use as a template in python.

This is my example code:

for x in range(1,10):
    tmp = open("test.md","r").read()
    print(tmp)

This is my text file (test.md):

{ x }

This is my current output:

{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }

I want this output:

1
2
3
4
5
....

Python 3 accepts { variable } in string ... how I can do that in this situation? Using f-string?

Upvotes: 3

Views: 8722

Answers (2)

han solo
han solo

Reputation: 6600

If you are doing something more rather than just print, i would suggest you use jinja2 (which is mainly used for html templating) like,

Requirments:

Create a virtualenv:

$ python3 -m venv venv
$ source ./venv/bin/activate

Install the jinja2 package:

$ pip install jinja2

Files:

$ cat tpl.py
import sys
from jinja2 import Environment, FileSystemLoader

file_loader = FileSystemLoader('.') # directory of template file
env = Environment(loader=file_loader)

template = env.get_template(sys.argv[1]) # load template file

output = template.render(values=range(10))
print(output)


$ cat tpl.txt
{% for value in values -%}
    {{ value }} 
{% endfor %}

Output:

$ python tpl.py tpl.txt
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 

Try another template:

$ cat tpl2.txt
{% for value in values -%}
{% if value < 5 %}
{{- value }}
{% endif %}    
{%- endfor %}


$ python tpl.py tpl2.txt
0
1
2
3
4

A little too much ? :)

Upvotes: 3

chepner
chepner

Reputation: 532093

You read a string from the file; you need to invoke its format method.

with open("test.md", "r") as f:
    tmp = f.read()

for x in range(1, 10):
    print(tmp.format(x))

Note that the x in your template is unrelated to the name of the variable you use in the for loop.

As-is, this will fail, because '{ x }' is a different format than '{x}'. Either edit the file to provide valid formats, modify the template in-memory (e.g., tmp.replace(" ", "")), or provide the exact key in the call to format (tmp.format(**{" x ": x})).

Upvotes: 7

Related Questions