I have a template file cotaining $DATE and $TIME to be substituted by the current values.
This works fine as long as I have evruthing in the main program.
However I want to put the substitution bit into a subroutine e.g. lie this:
def substitute():
DATE = '20120209'
TIME = '1200'
f = open( 'template.txt' )
template = string.Template( ''.join(f.readlines()) )
f.close()
# substitute and save
f = open( 'current.txt', 'w+' )
f.writelines(template.safe_substitute( globals() ))
f.close()
As I said, this works fine if I have it in the main program. But in the def version it only works if DATE and TIME are already defined in the main program. Which I do dont want to do.
Any ideas what the problem could be?
Use
locals()instead ofglobals()so the local values forDATEandTIMEare substituted:PS.
is functionally equivalent to
but slower since it splits the file into lines, then rejoins them. You might as well use
f.read().