Generate temporary file names without creating actual file in Python Generate temporary file names without creating actual file in Python python python

Generate temporary file names without creating actual file in Python


If you want a temp file name only you can call inner tempfile function _get_candidate_names():

import tempfiletemp_name = next(tempfile._get_candidate_names())% e.g. px9cp65s

Calling next again, will return another name, etc. This does not give you the path to temp folder. To get default 'tmp' directory, use:

defult_tmp_dir = tempfile._get_default_tempdir()% results in: /tmp 


I think the easiest, most secure way of doing this is something like:

path = os.path.join(tempfile.mkdtemp(), 'something')

A temporary directory is created that only you can access, so there should be no security issues, but there will be no files created in it, so you can just pick any filename you want to create in that directory. Remember that you do still have to delete the folder after.

edit: In Python 3 you can now use tempfile.TemporaryDirectory() as a context manager to handle deletion for you:

with tempfile.TemporaryDirectory() as tmp:  path = os.path.join(tmp, 'something')  # use path


It may be a little late, but is there anything wrong with this?

import tempfilewith tempfile.NamedTemporaryFile(dir='/tmp', delete=False) as tmpfile:    temp_file_name = tmpfile.namef = gzip.open(temp_file_name ,'wb')