HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

String replace templating utility

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
replacetemplatingstringutility

Problem

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 in the CSV file.

CSV Input File: test1.csv

The CSV file, which has header row, contains some catalog data, one product per row, like below:

stockID,color,material,url
340,Blue and magenta,80% Wool / 20% Acrylic,http://placehold.it/400
275,Purple,100% Cotton,http://placehold.it/600
318,Blue,100% Polyester,http://placehold.it/400x600


HTML Template Input File: testTemplate.htm

The HTML template file is simply a copy of the desired output with string replace tags %s placed at the appropriate locations:

Stock ID: %s


  • %s



  • %s





The Python is pretty straight forward I think. I open the template file and store it as a string. I then open the CSV file using the csv.dictreader() command. I then iterate through the rows of the CSV, build the file names and then write the output files using string replacement on the template string using the dictionary keys.

`import csv

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

# open CSV file that contains the data and store to a dictyionary 'inputFile'.
with open('test1.csv') as csvfile:
inputFile = csv.DictReader(csvfile)
x = 0 # counter to display file count
for row in inputFile:
# create filenames for the output HTML files
filename = 'listing'+row['stockID']+'.htm'
# print filenames for visual cue.
print(filename)
x = x + 1
# create output HTML file.
with open(filename, 'w') as outputFile:

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#82871, answer score: 12

Revisions (0)

No revisions yet.