Normally I process files in Python using a with statement, as in this chunk for downloading a resource via HTTP:
with (open(filename), "wb"):
for chunk in request.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
file.flush()
But this assumes I know the filename. Suppose I want to use tempfile.mkstemp()
. This function returns a handle to an open file and a pathname, so using open
in a with
statement would be wrong.
I've searched around a bit and found lots of warnings about being careful to use mkstemp
properly. Several blog articles nearly shout when they say do NOT throw away the integer returned by mkstemp
. There are discussions about the os-level filehandle being different from a Python-level file object. That's fine, but I haven't been able to find the simplest coding pattern that would ensure that
mkstemp
is called to get a file to be written to- after writing, the Python file and its underlying os filehandle are both closed cleanly even in the event of an exception. This is precisely the kind of behavior we can get with an
with(open...
pattern.
So my question is, is there a nice way in Python to create and write to a mkstemp
generated file, perhaps using a different kind of with statemement, or do I have to manually do things like fdopen
or close
, etc. It seems there should be a clear pattern for this.