【问题标题】:how to use tempfile.NamedTemporaryFile() in python如何在 python 中使用 tempfile.NamedTemporaryFile()
【发布时间】:2011-04-24 20:36:45
【问题描述】:

我想使用tempfile.NamedTemporaryFile() 将一些内容写入其中,然后打开该文件。我写了以下代码:

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

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

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

最后

【问题讨论】:

  • 为什么需要使用tempfile?你不能只使用一个普通的文件,特别是如果你想在以后保存它?
  • 我不想将它保存在我的系统上。我只想将这些内容作为记事本或类似应用程序中的文本打开,并在我关闭该应用程序时删除文件

标签: python file-io temporary-files


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    import tempfile
    with tempfile.NamedTemporaryFile() as temp:
        temp.write('Some data')
        temp.flush()
    
        # do something interesting with temp before it is destroyed
    

    【讨论】:

    • 请记住,您不能真正将temp.name 传递给其他进程以在 Windows(这似乎是 OP 的平台)上对其进行处理。来自手册:“名称是否可用于第二次打开文件,而命名的临时文件仍处于打开状态,因平台而异(它可以在 Unix 上如此使用;它不能在 Windows NT 或更高版本上)。
    • 不确定它是否有任何帮助,但 Django 覆盖了 NamedTemporaryFile,因此它可以与 Windows 一起使用,因此可能值得看看他们为实现这一目标所做的工作:code.djangoproject.com/wiki/NamedTemporaryFile
    • 看来调用flush 是必要的(否则,我在调用从文件读取的子进程中收到错误)。
    • Flush 不一定会将文件写入磁盘
    • 您应该使用with tempfile.NamedTemporaryFile(mode='w+t') as temp:,以便您可以将字符串文本实际写入文件。您现在所拥有的以二进制模式打开临时文件。
    【解决方案3】:

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

    首先,默认临时文件是deleted as soon as it is closed。要解决此问题:

    tf = tempfile.NamedTemporaryFile(delete=False)
    

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

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

    【讨论】:

    • 那么当我完成它时最好的删除方法是什么? tf.unlink? os.remove? path.remove?
    • @ThomasAhle 你会用什么?
    • 您需要添加导入:import tempfile 才能使用。
    • 如果我使用 delete=False,但使用上下文管理器(使用 tempfile.NamedTemporaryFile() 作为 temp:),它是否仍然会在文件超出范围时删除文件(而不是在已关闭),还是我仍然需要手动删除它?
    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-09-13
    • 1970-01-01
    • 2013-09-17
    • 2019-07-31
    • 2011-01-21
    相关资源
    最近更新 更多