Generate temporary file names without creating actual file in Python Ask Question

Generate temporary file names without creating actual file in Python Ask Question

Answers to Best way to generate random file names in Python show how to create temporary files in Python.

I only need to have a temporary file name in my case.
Calling tempfile.NamedTemporaryFile() returns a file handle after actual file creation.

Is there a way to get a filename only? I tried this:

# Trying to get temp file path
tf = tempfile.NamedTemporaryFile()
temp_file_name = tf.name
tf.close()
# Here is my real purpose to get the temp_file_name
f = gzip.open(temp_file_name ,'wb')
...

ベストアンサー1

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

おすすめ記事