如何在 Python 中使用 tempfile.NamedTemporaryFile()
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是两个原因之一:
首先,默认情况下,临时文件会尽快删除因为它已关闭。要修复此问题,请使用:
然后在其他应用程序中查看完该文件后手动删除该文件。
或者,也可能是因为文件仍在 Python 中打开,Windows 不允许您使用其他应用程序打开它。
编辑:回答评论中的一些问题:
从 2 当使用
delete=False
时,可以使用以下方法删除文件: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:
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:您还可以将其与上下文管理器一起使用,以便文件超出范围时将被关闭/删除。如果上下文管理器中的代码引发,它也会被清理。
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.
这是一个有用的上下文管理器。
(在我看来,这个功能应该是Python标准库的一部分。)
Here is a useful context manager for this.
(In my opinion, this functionality should be part of the Python standard library.)