创建文件后可以更改 NamedTemporaryFile 的删除标志吗?
创建此类文件后,如何更改 NamedTemporaryFile 的删除标志?
为什么?虽然大多数时候我不需要保留临时文件,但如果我从代码内部检测到错误,我想保留它们以便能够分析它们。
How can I change the delete flag from a NamedTemporaryFile after the creation of such file?
Why? While most of the time I don't need to keep temporary files, if I detect an error from inside the code I want to keep them in order to be able to analyse them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于现在在谷歌上搜索这个问题的人来说,至少对于 Python 3+ 而言,在实例化
NamedTemporaryFile
后更改delete
不会改变其初始行为,因为实际的标志存储在一个名为_closer
(这是一个_TemporaryFileCloser
实例)。请参阅 Python 中的tempfile.py
,作为官方 Python 文档 不要提及任何事情。因此,您要么更改此未记录属性:
或者始终使用
NamedTemporaryFile(delete=False)
创建,然后如果您不再需要该文件,则手动删除该文件。For anybody now googling this question, at least for Python 3+, changing
delete
after instantiatingNamedTemporaryFile
does not change its initial behaviour, because the actual flag is stored in a object called_closer
(which is a_TemporaryFileCloser
instance). Seetempfile.py
in Python, as the official Python docs don't mention anything.So you either change this undocumented attribute:
Or you always create with
NamedTemporaryFile(delete=False)
, and then delete the file manually if you don't want the file anymore.根据源代码,delete 只是存储为
NamedTemporaryFile
返回的对象的一个属性,因此您可以在关闭它之前进行任意修改。编辑:这对于 Python 2 来说是正确的;对于 Python 3,请参阅 Augusto Men 的回答。
According to the source code, delete is just stored as an attribute of the object returned by
NamedTemporaryFile
, so you can modify as much as you want before closing it.EDIT : this is true for Python 2 ; for Python 3, see Augusto Men's answer.