Python write in mkstemp() file

mkstemp returns (fd, name) where fd is an os-level file descriptor ready for writing in binary mode; so all you need is to use os.write(fd, 'TEST\n'), and then os.close(fd).

No need to re-open the file using either open or os.fdopen.

jcomeau@bendergift:~$ python
Python 2.7.16 (default, Apr  6 2019, 01:42:57) 
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> from tempfile import mkstemp
>>> fd, name = mkstemp()
>>> os.write(fd, 'TEST\n')
5
>>> print(name)
/tmp/tmpfUDArK
>>> os.close(fd)
>>> 
jcomeau@bendergift:~$ cat /tmp/tmpfUDArK 
TEST

In command-line testing, of course, there is no need to use os.close, since the file is closed on exit anyway. But that is bad programming practice.


mkstemp() returns a tuple with a file descriptor and a path. I think the issue is that you're writing to the wrong path. (You're writing to a path like '(5, "/some/path")'.) Your code should look something like this:

from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open the file at that path and close it again
with open(path, 'w') as f:
    f.write('TEST\n')

# close the file descriptor
os.close(fd)

This example opens the Python file descriptor with os.fdopen to write cool stuff, then close it (at the end of the with context block). Other non-Python processes can use the file. And at the end, the file is deleted.

import os
from tempfile import mkstemp

fd, path = mkstemp()

with os.fdopen(fd, 'w') as fp:
    fp.write('cool stuff\n')

# Do something else with the file, e.g.
# os.system('cat ' + path)

# Delete the file
os.unlink(path)

The answer by smarx opens the file by specifying path. It is, however, easier to specify fd instead. In that case the context manager closes the file descriptor automatically:

import os
from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open (and close) file descriptor fd (which points to path)
with os.fdopen(fd, 'w') as f:
    f.write('TEST\n')

# This causes the file descriptor to be closed automatically

Tags:

Python

Mkstemp