Generate config file from template using Python search and replace.
Mr Zaug
matthew.herzog at gmail.com
Sat Nov 28 16:45:34 EST 2015
I need to generate a config file based on an existing "template" file. I need to replace a set of strings with other strings globally in the generated file.
Here is a snippet of the template file, where CONTENT_PATH and DAMPATH are two "placeholders" or variables. There are several other such placeholders.
$include "_dispatcher_publish_filters.any"
/1000 { /type "allow" /glob "* /CONTENT_PATH/*.html*" }
/1001 { /type "allow" /glob "POST /DAMPATH/www/*.html *" }
The script's user will be asked to type in unique values when prompted for DAMPATH or CONTENT_PATH.
Since I know the variables themselves are not going to change (because the contents of the template file don't spontaneously change) should I be using regex to search for them or is there a better way? I was planning on using re.sub but I don't know whether that's the best way. Here's what my script looks like today.
from sys import argv
import re
from os.path import exists
script, template_file = argv
print "Opening the template file..."
in_file = open(template_file)
lines = in_file.readlines()
print "What is the serial number of the site?",
_NNN = raw_input()
print "What is the brand, or product name?",
_BRAND = raw_input()
print "What is the content path?",
_CONTENT_PATH = raw_input()
out_file = open(_nnn + _brand + "_farm.any", 'w')
for line in lines:
re.sub('NNN', _NNN, line)
re.sub('BRAND, _BRAND', line)
re.sub('CONTENT_PATH', _CONTENT_PATH, line)
out_file.close()
More information about the Python-list
mailing list