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

发布于 2024-09-27 14:50:17 字数 395 浏览 7 评论 0原文

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

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

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

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

在最后。

我不想将该文件永久保存在我的系统上。我只想在记事本或类似应用程序中将内容作为文本打开,并在关闭该应用程序时删除该文件。

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 can't I do something like:

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

at the end.

I don't want to save the file permanently on my system. I just want the contents to be opened as a text in Notepad or similar application and delete the file when I close that application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南街女流氓 2024-10-04 14:50:17

这可能是两个原因之一:

首先,默认情况下,临时文件会尽快删除因为它已关闭。要修复此问题,请使用:

tf = tempfile.NamedTemporaryFile(delete=False)

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

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

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

2 当使用 delete=False 时,可以使用以下方法删除文件:

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

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.

Edit: to answer some questions from the comments:

As of the docs from 2 when using delete=False the file can be removed by using:

 tf.close()
 os.unlink(tf.name)
满栀 2024-10-04 14:50:17

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

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

    # do something interesting with temp before it is destroyed

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
素罗衫 2024-10-04 14:50:17

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文