how to use tempfile.NamedTemporaryFile() in python

PythonFile IoTemporary Files

Python Problem Overview


I want to use tempfile.NamedTemporaryFile() to write some contents into it and then open that file. I have written following code:

tf = tempfile.NamedTemporaryFile()
tfName = tf.name
tf.seek(0)
tf.write(contents)
tf.flush()

but I am unable to open this file and see its contents in notepad or similar application. Is there any way to achieve this? Why cant I do something like:

os.system('start notepad.exe ' + tfName)

at the end

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManojView Question on Stackoverflow
Solution 1 - PythonDave WebbView Answer on Stackoverflow
Solution 2 - PythonJay PrallView Answer on Stackoverflow
Solution 3 - PythonHuguesView Answer on Stackoverflow