Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use tempfile.NamedTemporaryFile() in python

People also ask

What is Tempfile NamedTemporaryFile ()?

Source code: Lib/tempfile.py. This module creates temporary files and directories. It works on all supported platforms. TemporaryFile , NamedTemporaryFile , TemporaryDirectory , and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.

How does Tempfile work Python?

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.

How do I create a Tempfile in Python?

To create one temporary file in Python, you need to import the tempfile module. As explained above, we have created the temporary file using the TemporaryFile() function. From the output, you can see that the created object is actually not a file, it is a file-like object.


This could be one of two reasons:

Firstly, by default the temporary file is deleted as soon as it is closed. To fix this use:

tf = tempfile.NamedTemporaryFile(delete=False)

and then delete the file manually once you've finished viewing it in the other application.

Alternatively, it could be that because the file is still open in Python Windows won't let you open it using another application.


You can also use it with a context manager so that the file will be closed/deleted when it goes out of scope. It will also be cleaned up if the code in the context manager raises.

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    temp.write('Some data')
    temp.flush()

    # do something interesting with temp before it is destroyed

Here is a useful context manager for this. (In my opinion, this functionality should be part of the Python standard library.)

# python2 or python3
import contextlib
import os

@contextlib.contextmanager
def temporary_filename(suffix=None):
  """Context that introduces a temporary file.

  Creates a temporary file, yields its name, and upon context exit, deletes it.
  (In contrast, tempfile.NamedTemporaryFile() provides a 'file' object and
  deletes the file as soon as that file object is closed, so the temporary file
  cannot be safely re-opened by another library or process.)

  Args:
    suffix: desired filename extension (e.g. '.mp4').

  Yields:
    The name of the temporary file.
  """
  import tempfile
  try:
    f = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
    tmp_name = f.name
    f.close()
    yield tmp_name
  finally:
    os.unlink(tmp_name)

# Example:
with temporary_filename() as filename:
  os.system('echo Hello >' + filename)
  assert 6 <= os.path.getsize(filename) <= 8  # depending on text EOL
assert not os.path.exists(filename)