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.