Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate temporary file names without creating actual file in Python

People also ask

How do you name a temporary file in Python?

You just want a file object (pointing to an empty file) which has a filename associated to it and hence you cannot use a StringIO object: from tempfile import NamedTemporaryFile f = NamedTemporaryFile() # use f .. Once f is garbage collected, or closed explicitly, the file will automatically be removed from disk.

How do I create a tmp file?

To create and use a temporary file The application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.


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

import tempfile

temp_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 tempfile
with tempfile.NamedTemporaryFile(dir='/tmp', delete=False) as tmpfile:
    temp_file_name = tmpfile.name
f = gzip.open(temp_file_name ,'wb')

tempfile.mktemp() do this.

But note that it's deprecated. However it will not create the file and it is a public function in tempfile compared to using the _get_candidate_names().

The reason it's deprecated is due to the time gap between calling this and actually trying to create the file. However in my case the chance of that is so slim and even if it would fail that would be acceptable. But it's up to you to evaluate for your usecase.