Python - How to convert an "OS level descriptor to an open file" into a file?

tempfile.mkstemp () returns:

a tuple containing the OS level descriptor for the open file (which will be returned by os.open ()) and the absolute path to this file in that order.

How to convert this OS level descriptor to a file object?

The documentation for os.open () states:

To wrap the 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 
+47
python temporary-files mkstemp
Oct 03 '08 at 19:41
source share
6 answers

you can use

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

to write to the descriptor.

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

 f = os.fdopen(tup[0], "w") f.write("foo") 
+48
03 Oct '08 at 19:47
source share

Here's how to do it using the 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') 
+13
Aug 18 '09 at 19:44
source share

You forgot to specify open mode ('w') in fdopen (). The default value is "r", as a result of which the write () call failed.

I think mkstemp () creates a read-only file. Calling fdopen with "w" probably opens it for writing (you can open the file created by mkstemp again).

+6
Oct 03 '08 at 20:00
source share
 temp = tempfile.NamedTemporaryFile(delete=False) temp.file.write('foo\n') temp.close() 
+4
Mar 10
source share

What is your goal here? Is tempfile.TemporaryFile unacceptable for your purposes?

+1
Oct 03 '08 at
source share

I can not 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, for example:

 f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'... os.write(f[0], "write something") 
0
Jun 05 '13 at 14:15
source share



All Articles