如何在python中使用tempfile.namedTemporaryFile() [英] how to use tempfile.NamedTemporaryFile() in python

查看:169
本文介绍了如何在python中使用tempfile.namedTemporaryFile()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 tempfile.NamedTemporaryFile()来写入一些内容,然后打开这个文件。我已经写了下面的代码:

$ $ $ $ $ $ c $ t $ tempfile.namedTemporaryFile $ b $ tfName = tf.name
tf.seek(0)
tf.write(contents)
tf.flush()

但我无法打开此文件,并在记事本或类似的应用程序中看到它的内容。有没有办法做到这一点?为什么不能这样做:

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

最后

解决方案

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

首先,临时文件默认是一旦关闭就会被删除。为了解决这个问题:

$ $ $ code $ t $ tempfile.namedTemporaryFile(delete = False)



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



或者,也可能是因为Python中的文件仍然打开,Windows不会让你使用其他应用程序打开它。


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 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中使用tempfile.namedTemporaryFile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆