Python - How do I convert "an OS-level handle to an open file" to a file object? Python - How do I convert "an OS-level handle to an open file" to a file object? python python

Python - How do I convert "an OS-level handle to an open file" to a file object?


You can use

os.write(tup[0], "foo\n")

to write to the handle.

If you want to open the handle for writing you need to add the "w" mode

f = os.fdopen(tup[0], "w")f.write("foo")


Here's how to do it using a with statement:

from __future__ import with_statementfrom contextlib import closingfd, filepath = tempfile.mkstemp()with closing(os.fdopen(fd, 'w')) as tf:    tf.write('foo\n')


You forgot to specify the open mode ('w') in fdopen(). The default is 'r', causing the write() call to fail.

I think mkstemp() creates the file for reading only. Calling fdopen with 'w' probably reopens it for writing (you can reopen the file created by mkstemp).