Python:防止在关闭时删除临时文件

Dag*_*ang 1 python

我需要创建一个临时文件,其中包含一些测试内容:

def test_something():
  tmp_path = make_temp_file('hello\nworld')
  do_something(tmp_path)
Run Code Online (Sandbox Code Playgroud)

但我用来使文件在关闭时自动删除文件的以下代码:

  def make_temp_file(text):
    with tempfile.NamedTemporaryFile() as tmp_file:
      tmp_file.write(text.encode('utf-8'))
      tmp_file.flush()
      return tmp_file.name
Run Code Online (Sandbox Code Playgroud)

所以,在do_something(tmp_path)文件中没有找到。如何防止关闭时删除 tmp 文件?测试完后我会手动删除它。

Dag*_*ang 8

有一个删除参数,默认为 true。所以代码应该tempfile.NamedTemporaryFile(delete=False)在示例中。

感谢@juanpa.arrivilillaga。