As tempfile.mktemp is depreciated in Python 2.7 I generate a unique path to a temporary file as follows:
temp = tempfile.NamedTemporaryFile(suffix=".py")
path_to_generated_py = temp.name
temp.close()
# now I use path_to_gerated_py to create a python file
Is this the recommended way in Python 2.7? As I close the temp file immediately it looks like misusing NamedTemporaryFile….
The direct replacement for
tempfile.mktemp()istempfile.mkstemp(). The latter creates the file, likeNamedTemporaryFile, so you must close it (as in your code snippet). The difference withNamedTemporaryFileis that the file is not deleted when closed. This is actually required: your version has a theoretical race condition where two processes might end up with the same temporary file name. If you usemkstemp()instead, the file is never deleted, and will likely be overwritten by the 3rd-party library you use — but at any point in time, the file exists, and so there is no risk that another process would create a temporary file of the same name.