Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call tempfile.mkstemp() with "with"? - or why doesn't it return an fd with __exit__()?

To me the most idiomatic way of calling tempfile.mkstemp() would be as:

with tempfile.mkstemp() as fd, filename:
    pass

however, this obviously(?) raises AttributeError: __exit__

Calling os.close(fd) explicitly using try-finally is an easy way to solve this, but feels like violation of There should be one-- and preferably only one --obvious way to do it.

Is there a way to "fix" this in tempfile or is there a rationale why this has been implemented this way?

like image 741
Kimvais Avatar asked Aug 27 '13 06:08

Kimvais


1 Answers

In the tempfile module there are other, better suited ways to create a temporary file, such as TemporaryFile() and others.

Especially, if you don't want the file to be deleted, use NamedTemporaryFile(), giving it the delete=False argument.

like image 79
glglgl Avatar answered Oct 25 '22 01:10

glglgl