pythontemporary-filesmkstempfdopen

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


tempfile.mkstemp() returns:

a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

How do I convert that OS-level handle to a file object?

The documentation for os.open() states:

To wrap a file descriptor in a "file object", use fdopen().

So I tried:

>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor

Solution

  • 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")