简体   繁体   English

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

[英]how to use tempfile.NamedTemporaryFile() in python

I want to use tempfile.NamedTemporaryFile() to write some contents into it and then open that file. 我想使用tempfile.NamedTemporaryFile()将一些内容写入其中,然后打开该文件。 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 在末尾

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. 或者,它可能是因为文件仍然在Python中打开Windows不允许您使用其他应用程序打开它。

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.) (在我看来,这个功能应该是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用tempfile.NamedTemporaryFile()? - How to use tempfile.NamedTemporaryFile()? 如何使用 tempfile.NamedTemporaryFile() 保存图像? - How to use tempfile.NamedTemporaryFile() to save an image? Python&gt; 3中的tempfile.TemporaryFile和tempfile.NamedTemporaryFile是否相同 - Are tempfile.TemporaryFile and tempfile.NamedTemporaryFile same in Python > 3 如何打开(两次)使用tempfile.NamedTemporaryFile()创建的文件 - How do I open (twice) file created with tempfile.NamedTemporaryFile() 我可以在 python 中为 tempfile.NamedTemporaryFile 设置 umask 吗? - Can I set the umask for tempfile.NamedTemporaryFile in python? 任务计划程序中的tempfile.NamedTemporaryFile崩溃 - tempfile.NamedTemporaryFile crashing in Task Scheduler 如何阻止 tempfile.NamedTemporaryFile 在临时文件前缀的末尾添加随机字符? - How to stop tempfile.NamedTemporaryFile from adding random characters to the end of the temp file prefix? Python 2.7 tempfile.NamedTemporaryFile返回类型为“实例”而不是“文件”的对象。 为什么? - Python 2.7 tempfile.NamedTemporaryFile returns object in type 'instance' not 'file'. Why? python 临时文件 | NamedTemporaryFile 不能使用生成的临时文件 - python tempfile | NamedTemporaryFile can't use generated tempfile 为什么tempfile.NamedTemporaryFile()会截断我的数据? - Why does tempfile.NamedTemporaryFile() truncate my data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM