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

Man*_*noj 40 python file-io temporary-files

我想用它tempfile.NamedTemporaryFile()来写一些内容然后打开那个文件.我写了以下代码:

tf = tempfile.NamedTemporaryFile()
tfName = tf.name
tf.seek(0)
tf.write(contents)
tf.flush()
Run Code Online (Sandbox Code Playgroud)

但我无法打开此文件,并在记事本或类似的应用程序中查看其内容.有没有办法实现这个目标?为什么我不能这样做:

os.system('start notepad.exe ' + tfName)
Run Code Online (Sandbox Code Playgroud)

在末尾

Dav*_*ebb 48

这可能是以下两个原因之一:

首先,默认情况下,临时文件一关闭就会删除.要解决此问题:

tf = tempfile.NamedTemporaryFile(delete=False)
Run Code Online (Sandbox Code Playgroud)

然后在其他应用程序中完成查看后手动删除该文件.

或者,它可能是因为文件仍然在Python中打开Windows不允许您使用其他应用程序打开它.

  • 那么当我完成它之后删除它的最佳方法是什么?`tf.unlink`?`os.remove`?`path.remove`? (28认同)
  • 如果我使用 delete=False,但使用上下文管理器(使用 tempfile.NamedTemporaryFile() 作为临时 :),当文件超出范围时(与关闭时相反),它是否仍然删除文件,或者我仍然必须手动删除吗? (8认同)

Jay*_* P. 38

您还可以将其与上下文管理器一起使用,以便在文件超出范围时关闭/删除该文件.如果上下文管理器中的代码引发,它也将被清除.

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

    # do something interesting with temp before it is destroyed
Run Code Online (Sandbox Code Playgroud)

  • 请记住,您无法将`temp.name`传递给其他进程,以便在Windows上执行某些操作(这似乎是OP的平台).从手册:"名称是否可用于第二次打开文件,而命名的临时文件仍然打开,因平台而异(它可以在Unix上使用;它不能在Windows NT或更高版本上使用)." (8认同)
  • 您应该使用“with tempfile.NamedTemporaryFile(mode='w+t') as temp:”,以便您可以实际将字符串文本写入文件。您现在所拥有的以二进制模式打开临时文件。 (3认同)
  • 似乎需要调用`flush`(否则,我在调用从文件中读取的子进程中出错). (2认同)

Hug*_*ues 13

这是一个有用的上下文管理器。(在我看来,这个功能应该是 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)
Run Code Online (Sandbox Code Playgroud)