sorin sorin - 1 year ago 80
Python Question

Can you change the delete flag from a NamedTemporaryFile after the file was created?

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.

Answer Source

For anybody now googling this question, at least for Python 3+, changing delete after instantiating NamedTemporaryFile does not change its initial behaviour, because the actual flag is stored in a object called _closer (which is a _TemporaryFileCloser instance). See in Python, as the official Python docs don't mention anything.

So you either change this undocumented attribute:

f = tempfile.NamedTemporaryFile(delete=True)
# f.delete = False  # This doesn't change anything
f._closer.delete = False  # undocumented
f.close()  # the file won't be deleted

Or you always create with NamedTemporaryFile(delete=False), and then delete the file manually if you don't want the file anymore.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download