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

PythonTemporary FilesMkstempFdopen

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

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

Solution 3 - Python

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).

Solution 4 - Python

temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write('foo\n')
temp.close()

Solution 5 - Python

What's your goal, here? Is tempfile.TemporaryFile inappropriate for your purposes?

Solution 6 - Python

I can't comment on the answers, so I will post my comment here:

To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:

f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
os.write(f[0], "write something")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaryl SpitzerView Question on Stackoverflow
Solution 1 - PythonPeter HoffmannView Answer on Stackoverflow
Solution 2 - PythonDaryl SpitzerView Answer on Stackoverflow
Solution 3 - PythonefotinisView Answer on Stackoverflow
Solution 4 - PythonhojuView Answer on Stackoverflow
Solution 5 - PythonAlex CoventryView Answer on Stackoverflow
Solution 6 - PythonMartinDView Answer on Stackoverflow