如何在Python中使用tempfile.NamedTemporaryFile()

78 投票
3 回答
133759 浏览
提问于 2025-04-16 05:25

我想用 tempfile.NamedTemporaryFile() 来写一些内容到一个临时文件里,然后再打开这个文件。我写了以下代码:

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

但是我无法在记事本或类似的应用程序中打开这个文件,查看它的内容。有没有什么办法可以做到这一点?为什么我不能在最后这样做:

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

我不想把文件永久保存到我的系统里。我只是想在记事本或类似的应用程序中打开这些内容,并在关闭那个应用程序时删除这个文件。

3 个回答

28

这里有一个很有用的上下文管理器。
(在我看来,这个功能应该是Python标准库的一部分。)

# 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)
79

你还可以用一个上下文管理器来使用它,这样当文件不再需要时,它会自动关闭或删除。如果在上下文管理器里的代码出错了,它也会被清理掉。

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

    # do something interesting with temp before it is destroyed
79

这可能有两个原因:

首先,默认情况下,临时文件在关闭后会被立即删除。要解决这个问题,可以使用:

tf = tempfile.NamedTemporaryFile(delete=False)

然后在你查看完这个文件后,可以手动删除它。

另外一个原因可能是,因为文件仍然在Python中打开,所以Windows不允许你用其他应用程序打开它。

编辑:为了回答一些评论中的问题:

根据文档,当使用delete=False时,可以通过以下方式删除文件:

 tf.close()
 os.unlink(tf.name)

撰写回答