Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file object from mkstemp()?

Tags:

python

file

I'm 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 is supposed to be a file handle. In fact, it's an int. How do I get a proper file object?

like image 315
Erik Avatar asked Aug 13 '12 00:08

Erik


2 Answers

In the documentation for mktemp you can see an example of how to use NamedTemporaryFile the 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.

like image 125
Tordek Avatar answered Oct 30 '22 08:10

Tordek


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

But if you have a raw FD from the underlying OS, you can do this to make it into a file object:

f = open(fd, closefd=True)

This works in Python 3

like image 42
l04m33 Avatar answered Oct 30 '22 09:10

l04m33