You can use the standard library string and its Template class.

Given an input file foo.txt:

$title
$subtitle
$list

And this code in example.py:

from string import Template

d = {
    'title': 'This is the title',
    'subtitle': 'And this is the subtitle',
    'list': '\n'.join(['first', 'second', 'third'])
}

with open('foo.txt', 'r') as f:
    src = Template(f.read())
    result = src.substitute(d)
    print(result)

Then run it:

$ python example.py
This is the title
And this is the subtitle
first
second
third
Answer from ThibThib on Stack Overflow
🌐
Python
docs.python.org › 3 › library › string.templatelib.html
string.templatelib — Support for template string literals
While literal syntax is the most common way to create a Template, it is also possible to create them directly using the constructor: >>> from string.templatelib import Interpolation, Template >>> cheese = 'Camembert' >>> template = Template( ... 'Ah!
Discussions

python - advanced string formatting vs template strings - Stack Overflow
If you, say, write a snippet of C code to a file with some strings replaced, a template string might be preferable since you don't need to double all braces to escape them, and since $ does not have any special meaning in C. 2012-07-24T13:12:19.19Z+00:00 ... Template strings can be more secure realpython.com/python-string-formatting/… 2020-01-14T08:51:34.03Z+00:00 ... For what it's worth, Template substitution from ... More on stackoverflow.com
🌐 stackoverflow.com
python - String replace templating utility - Code Review Stack Exchange
I am new to Python and I am writing my first utility as a way to learn about strings, files, etc. I am writing a simple utility using string replacement to batch output HTML files. The program takes as inputs a CSV file and an HTML template file and will output an HTML file for each data row ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 1, 2015
python how to convert from string.template object to string - Stack Overflow
fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb') html = Template(fp.read()) fp.close() html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu') print html · When i run this code in intepreter directly,I get the proper output. But when I run it from a file.I get More on stackoverflow.com
🌐 stackoverflow.com
How to save String Template as a Text file in Python 3? - Stack Overflow
I am taking data from .csv file and user to create a string template,Now I want to save this template as a text file.I have assigned the whole template into a single variable as Temp=A, t.substit... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › template-class-in-python
String Template Class in Python - GeeksforGeeks
July 23, 2025 - Explanation: This code creates a template with the string 'x is $x', where $x is a placeholder. Using the substitute method with {'x': 1}, it replaces $x with 1. Example 2: In this example, we loop through a list of students and print their marks using Template substitution. ... from string import Template a = [('Ram', 90), ('Ankit', 78), ('Bob', 92)] t = Template('Hi $name, you have got $marks marks') for i in a: print(t.substitute(name=i[0], marks=i[1]))
🌐
Python
wiki.python.org › moin › Templating
Templating - Python Wiki
Template Toolkit - Python port of Perl template engine · Templet - a 90-line BSD-licensed utility that defines @stringfunction and @unicodefunction python function decorators for simple, robust, and speedy templating.
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.4 documentation
The string module contains support for a simple templating approach based upon regular expressions, via string.Template. This offers yet another way to substitute values into strings, using placeholders like $x and replacing them with values from a dictionary.
🌐
Towards Data Science
towardsdatascience.com › home › latest › python template string formatting method
Python Template String Formatting Method | Towards Data Science
January 21, 2025 - Despite Template string being less powerful: viniciusmonteiro$ python3 -m timeit -s "x = 'f'; y = 'z'" "f'{x} {y}'" ... viniciusmonteiro$ python3 -m timeit -s "from string import Template; x = 'f'; y = 'z'" "Template('$x $y').substitute(x=x, y=y)" # template string
🌐
YouTube
youtube.com › watch
How to Generate File Reports Using Python's string.Template Class - YouTube
In this Python tutorial, you will learn how to automatically generate file reports using Python's string.Template class.First, we'll have a look at the motiv...
Published   October 26, 2021
Top answer
1 of 6
41

One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:

"Hello, {first} {last}".format(first='Joe')

raises:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'last'

But:

from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')

Produces:

'Hello, Joe $last'

Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.

2 of 6
29

Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python's %-style string formatting:

Python currently supports a string substitution syntax based on C's printf() '%' formatting character. While quite rich, %-formatting codes are also error prone, even for experienced Python programmers. A common mistake is to leave off the trailing format character, e.g. the s in %(name)s.

In addition, the rules for what can follow a % sign are fairly complex, while the usual application rarely needs such complexity. Most scripts need to do some string interpolation, but most of those use simple "stringification" formats, i.e. %s or %(name)s This form should be made simpler and less error prone.

While the new .format() improved the situation, it's still true that the format string syntax is rather complex, so the rationale still has its points.

Find elsewhere
🌐
Python
peps.python.org › pep-0750
PEP 750 – Template Strings - Python Enhancement Proposals
July 8, 2024 - Thankfully, because Template and ... equivalent Template instance: def from_format(fmt: str, /, *args: object, **kwargs: object) -> Template: """Parse `fmt` and return a `Template` instance.""" ... # Load this from a file, database, ...
🌐
Stack Abuse
stackabuse.com › formatting-strings-with-the-python-template-class
Formatting Strings with the Python Template Class
September 19, 2021 - In a template string, $name and $age would be considered valid placeholders. To use the Python Template class in our code, we need to: ... >>> from string import Template >>> temp_str = 'Hi $name, welcome to $site' >>> temp_obj = Template(temp_str) >>> temp_obj.substitute(name='John Doe', site='StackAbuse.com') 'Hi John Doe, welcome to StackAbuse.com'
Top answer
1 of 3
12

Python has a number of templating options, but the simplest to start is probably the string.Template one described in https://docs.python.org/3/library/string.html#template-strings

This supports targets such as $StockId and is used as below

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

If you need more output options, look at the string.format functionality, but this is probably best for starting with.

2 of 3
5

Style

Python has a style guide called PEP8. Among many other great things, it gives guidelines about spacing that you do not follow. Indeed, your spacing seems to be quite inconsistent. You'll find tools such as pep8 to check your compliancy to PEP8 and other tools such as ``autopep8 to fix your code automatically.

It can be a good habit to move the part of your program doing things (by opposition to the part of your program defining things) behind an if __name__ == "__main__" guard.

You can also use tools such as pylint to check your code. Among other things, Python naming convention are now followed.

Don't repeat yourself / avoid magic numbers

I can see 30 in multiples places. This is usually a bad sign : if you ever want to change the value to something else, you'll have to change it in multiple places. You probably should define a constant to hold that value behind a meaningful name.

Even better, you could define a function to perform the particular behavior that you want :

Getting the length the right way

At the moment, you are keeping track of the number of rows in input_file by incrementing a variable x. It is much clearer to simply use len(intput_file). Also, x = x + 1 can simply be written : x += 1.

Taking these various comments into account, you get :

import csv

SIZE_LINE = 30


def print_with_line(s):
    print(s)
    print('-' * SIZE_LINE)


if __name__ == '__main__':

    # Open template file and pass string to 'data'.
    # Should be in HTML format except with string replace tags.
    with open('testTemplate.htm', 'r') as my_template:
        data = my_template.read()
        # print template for visual cue.
        print_with_line('Template passed:')
        print_with_line(data)

    # open CSV file that contains the data and
    # store to a dictyionary 'input_file'.
    with open('test1.csv') as csv_file:
        input_file = csv.DictReader(csv_file)
        for row in input_file:
            # create filenames for the output HTML files
            filename = 'listing' + row['stockID'] + '.htm'
            # print filenames for visual cue.
            print(filename)
            # create output HTML file.
            with open(filename, 'w') as output_file:
                # run string replace on the template file
                # using items from the data dictionary
                # HELP--> this is where I get nervous because
                # chaos will reign if the tags get mixed up
                # HELP--> is there a way to add identifiers to
                # the tags?  like %s1 =row['stockID'], %s2=row['color'] ... ???
                output_file.write(data % (
                    row['stockID'],
                    row['color'],
                    row['material'],
                    row['url']))

    # print the number of files created as a cue program has finished.
    print_with_line(str(len(input_file)) + ' files created.')
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.4 documentation
This is the object passed to the constructor’s template argument. In general, you shouldn’t change it, but read-only access is not enforced. ... >>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes kung pao' >>> d = dict(who='tim') >>> Template('Give $who $100').substitute(d) Traceback (most recent call last): ...
🌐
Medium
medium.com › @bluebirz › 3-ways-for-python-string-template-71d2bb5d3de1
3 ways for Python string template | by bluebirz | Medium
January 28, 2025 - There is an innate library we can use to format a string in a more flexible way without installing any third-party libraries. It is a string template. Just from String import Template and it's ready.
🌐
Medium
pavolkutaj.medium.com › write-text-and-populate-a-new-file-from-template-with-python-165c2cad38ad
Write Text And Populate a New File From Template with Python | by Pavol Z. Kutaj | Medium
January 27, 2021 - create an empty markdown file with the title from an input · populate with a template text · even though you don’t have to pass selector, it is recommended for the sake of readability · as far as the write –vs– append goes: the write mode erases the previous file data · the append mode attaches the content to the file · also, it is highly recommended to pass encoding=utf-8 (or any other desired one) the write() method writes a string to a stream ·
🌐
Florian-dahlitz
florian-dahlitz.de › articles › generate-file-reports-using-pythons-template-class
Generate File Reports Using Python's Template Class - Florian Dahlitz
November 26, 2020 - In this article, you will learn how to utilise Python's string.Template class to generate file reports.
🌐
Reddit
reddit.com › r/python › template strings in python 3.14: an useful new feature or just an extra syntax?
r/Python on Reddit: Template strings in Python 3.14: an useful new feature or just an extra syntax?
May 1, 2025 -

Python foundation just accepted PEP 750 for template strings, or called t-strings. It will come with Python 3.14.

There are already so many methods for string formatting in Python, why another one??

Here is an article to dicsuss its usefulness and motivation. What's your view?

🌐
Real Python
realpython.com › python-string-formatting
Python String Formatting: Available Tools and Their Features – Real Python
December 2, 2024 - The different types of string formatting in Python include f-strings for embedding expressions inside string literals, the .format() method for creating string templates and filling them with values, and the modulo operator (%), an older method used in legacy code similar to C’s printf() function.