0

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)
Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • How about creating a temp directory instead and create non-temp files inside that? – ollik1 Sep 25 '21 at 13:54
  • mmm I'd prefer my approach if possible – Gabriel Sep 25 '21 at 13:58
  • Did you look here ? https://stackoverflow.com/questions/39592524/temp-files-directories-with-custom-names – balderman Sep 25 '21 at 14:12
  • I had not seen that question and its answer. I guess it's not possible to define a custom name with `NamedTemporaryFile()` then – Gabriel Sep 25 '21 at 14:17
  • From here: https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile, it says: *That name can be retrieved from the name attribute of the returned file-like object*. Maybe if you try to retrieve it and change it. But I am not sure if it is possible to change the name, while the file is open. But because `delete=False`, maybe you can close it and rename it. – LoukasPap Sep 25 '21 at 14:35
  • Yes, that's what @balderman was pointing at – Gabriel Sep 25 '21 at 14:40
  • I don't undestand - if you want custom name `/tmp/210925_104246.py` then you don't need `tempfile` but only `strftime("/tmp/%y%m%d_%H%M%S.py")` – furas Sep 25 '21 at 17:40
  • I don't know why you need this but maybe you need [cookiecutter](https://cookiecutter.readthedocs.io/en/1.7.0/README.html) which can generate project using templates. – furas Sep 25 '21 at 17:45
  • `then you don't need tempfile` I wanted something specifically aimed at creating tempfiles that was cross-platform – Gabriel Sep 25 '21 at 17:53
  • you can get path to source code `print( tempfile.__file__ )` and then you can copy this code to create own version. – furas Sep 25 '21 at 18:47
  • 1
    digging in source code I found function `tempfile.gettempdir()` which gives `/tmp` on Linux and probably it gives other temporary folder on Windows - so you could use it to create cross-platform code. – furas Sep 25 '21 at 18:51

1 Answers1

0

I did go through the official doc for Tempfile and I think there isn't a way to give it a custom name (except the prefix and suffix, which you've already used).

However, if you're looking for a way to store your boilerplate code in a file and then retrieve it later in your code, you could consider using pickle like this:

import tempfile
import datetime
import pickle
import os

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(bp_code):

    pref = datetime.datetime.now().strftime("%y%m%d_%H%M%S") + ".py"
#     f = tempfile.NamedTemporaryFile(delete=False, suffix=".py", prefix=pref)
#     filepath = f.name
    filedir = "d:\mycode"
    
    filename = os.path.join(filedir, pref)
    with open(filename, 'wb') as fh:
        pickle.dump(bp_code, fh)
        
    return filename

def getBoilerPlateCode(fpath):
    bp_code =""
    with open(fpath, 'rb') as fh:
        bp_code = pickle.load(fh)
    return bp_code.decode('utf-8')

filepath = createFile(boiler)
print(f"Filepath: {filepath}")

repeated_code = getBoilerPlateCode(filepath)
print(repeated_code)
Shine J
  • 798
  • 1
  • 6
  • 11