Skip to content

Instantly share code, notes, and snippets.

Last active April 4, 2018 12:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mightyCelu/2565695c949c2e97ed98d377ef7c3b19 to your computer and use it in GitHub Desktop.
Helper to replace parts of a file with corresponding values
import os
from string import Template
def configure_file(template_filename, out, **kwargs):
"""Rewrites placeholders within the file according to the given argument
The file specified by template_filename is read. Occurences of template values (e.g. identifiers prefixed with '$',
for more details see string.Template) are replaced with the corresponding keyword argument value. The resulting file
is written to out. If out is a directory, the template's filename is stripped of the '.in' extension and used as
the output's filename.
@param template_filename: The filename of the template to use. It must end with '.in'. The file must be readable.
@param out: A directory or file to write the configured file to.
@param kwargs: Keyword arguments are used to template the file.
if not os.path.isfile(template_filename):
raise ValueError('Template file does not exist')
if not (os.path.splitext(template_filename)[1] == '.in' and os.path.isfile(template_filename)):
raise ValueError('Given file is not a template file')
if not os.access(template_filename, os.R_OK):
raise ValueError('Cannot read template file')
if not os.access(out, os.W_OK):
raise ValueError('Cannot write output file')
if os.path.isdir(out):
output_path = os.path.join(out, os.path.splitext(os.path.basename(template_filename))[0])
elif os.path.isfile(out):
output_path = out
raise ValueError('Out is neither a directory nor a file.')
template = None
with open(template_filename, 'r') as template_file:
template = Template(
output_path = os.path.join(outdir, os.path.splitext(os.path.basename(template_filename))[0])
with open(output_path, 'w') as output_file:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment