How to get file object from mkstemp ()?

I am trying to use mkstemp with Python 3:

Python 3.2.3 (default, Jun 25 2012, 23:10:56) [GCC 4.7.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from tempfile import mkstemp >>> mkstemp() (3, '/tmp/tmp080316') 

According to the documentation, the first element of the tuple should be a file descriptor. This is actually an int. How to get the correct file object?

+8
python file
source share
3 answers

In the documentation for mktemp you can see an example of how to use NamedTemporaryFile way you want: http://docs.python.org/dev/library/tempfile.html?highlight=mkstemp#tempfile.mktemp

 >>> f = NamedTemporaryFile(delete=False) >>> f <open file '<fdopen>', mode 'w+b' at 0x384698> 

This provides the same behavior as mkstemp, but returns a file object.

+9
source share

The best way I know is to use tempfile.NamedTemporaryFile , as you can see in @tordek's answer.

But if you have the original FD from the base OS, you can do this to turn it into a file object:

 f = open(fd, closefd=True) 

This works in Python 3

+2
source share

int is an OS-level file descriptor. What I really need is a higher level file object. To do this, use:

 os_handle = mkstemp() f = open(mkstemp()[0]) 
0
source share

All Articles