07 February 2006 7 comments Python
I learnt something useful today which I can't explain. When you use the tempfile module in the Python standard library and the mkstemp() function you get two things back: an integer and a string.:
>>> import tempfile
>>> x, y = tempfile.mkstemp()
>>> x, type(x)
(3, <type 'int'>)
>>> y, type(y)
('/tmp/tmpK19sIx', <type 'str'>)
>>> help(tempfile.mkstemp)
I don't know what to do with the integer so I just ignore it. I thought I would get the result of open("/tmp/tmpK19sIx","w+b").
The help section of mkstemp says:
mkstemp(suffix='', prefix=tmp, dir=None, text=False)
mkstemp([suffix, [prefix, [dir, [text]]]])
User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
What does os.open do? My guess is that it's a lower level constructor than builtin open().
All I wanted to do was generate a temporary filename where I can place some binary content to be unpacked by another little script that uses tarfile. I had to do something like this:
def TGZFileToHTML(content):
__, tmp_name = tempfile.mkstemp(suffix='.tgz')
open(tmp_name, 'w+b').write(content)
result = tarfile2html(tmp_name)
os.remove(tmp_name)
return result
Is this the right way to do it? I first looked at tempfile.mktemp() but it's apparently not secure.
The lower level C library wrappers are not really necessary most of the time.
And Richard pointed it out but it deserves to be mentioned again. DO NOT THROW AWAY the integer returned by mkstemp if you choose to use it.
Really, don't.
f = os.fdopen(tmp_name, 'w+b')
f.write(content)
...
f = os.fdopen(tmp_fd, 'w+b')