views:

1795

answers:

5

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
+16  A: 

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")
Peter Hoffmann
That works--thanks. But technically fdopen returns a file object (and you pass in a file descriptor), so if I could edit your answer I'd change it to "f = os.fdopen(tup[0], "w");f.write("foo")
Daryl Spitzer
+5  A: 

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

efotinis
+1  A: 

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

fivebells
I don't want the file destroyed as soon as it's closed. (And I want to be sure the file to be visible.)
Daryl Spitzer
then you can pass delete=False to NamedTemporaryFile
Plumo
+1  A: 

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')
Daryl Spitzer
A: 

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

Plumo
The "delete" parameter was added in version 2.6, so that won't work for older Python versions.
alberge