Search code examples
pythontemporary-files

Python's tempfile.mkstemp() returning an integer instead of a file handle?


According to tempfile.mkstemp docs,

mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

However, from these shell commands, it looks like the first member of the tuple is an integer, not a file handle:

>>> temp = tempfile.mkstemp(suffix='.html')

>>> temp
(17, '/var/folders/dc/nv4yxcrd0zqd2dtxlj281b740000gn/T/tmpktmb2gjg.html')

>>> type(temp[0])
int

Do I have to get the file handle by using open(temp[1])? Why is it not returning a file handle?


Solution

  • That’s expected behaviour, because OS-level file handles are integers.

    There are several functions in the os module that’ll accept such integers:

    These functions operate on I/O streams referenced using file descriptors.

    File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.

    They are not Python file objects but you could create a Python file object for a given descriptor with io.FileIO().

    However, if all you wanted was a temporary file as a Python file object, just stick to the higher-level functions of the temp module, such as tempfile.TemporaryFile().