I'm trying to generate temp files containing some basic Python boilerplate code. I've got most of the code working, but I can't seem to figure out how to set the full name for the temporary file using the tempfile module.
My code (below) produces files names like /tmp/210925_104246et5p5tgz.py
where the first part (210925_104246
) is the time-stamp I want to use as the name. The characters between that and the .py
(et5p5tgz
) are automatically generated by the NamedTemporaryFile()
function and I don't know how to prevent that.
import tempfile
import datetime
boiler = b'''
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii
def main():
"""
"""
def func():
"""
"""
return
if __name__ == '__main__':
main()
'''
def createFile():
"""
"""
pref = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
f = tempfile.NamedTemporaryFile(delete=False, suffix=".py", prefix=pref)
filepath = f.name
f.write(boiler)
f.close()
return filepath
filepath = createFile()
print(filepath)