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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With