簡體   English   中英

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

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

我想使用tempfile.NamedTemporaryFile()將一些內容寫入其中,然后打開該文件。 我寫了以下代碼:

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

但我無法打開此文件,並在記事本或類似的應用程序中查看其內容。 有沒有辦法實現這個目標? 為什么我不能這樣做:

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

在末尾

這可能是以下兩個原因之一:

首先,默認情況下,臨時文件一關閉就會刪除 要解決此問題:

tf = tempfile.NamedTemporaryFile(delete=False)

然后在其他應用程序中完成查看后手動刪除該文件。

或者,它可能是因為文件仍然在Python中打開Windows不允許您使用其他應用程序打開它。

您還可以將其與上下文管理器一起使用,以便在文件超出范圍時關閉/刪除該文件。 如果上下文管理器中的代碼引發,它也將被清除。

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

    # do something interesting with temp before it is destroyed

這是一個有用的上下文管理器。 (在我看來,這個功能應該是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM