from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
    tf.write('foo\n')
Python - How do I convert "an OS-level handle to an open file" to a file object?