0

I need to create a temporary file to write some data out to in Python 3. The file will be written to via a separate module which deals with opening the file from a path given as a string.

I'm using tempfile.mkstemp() to create this temporary file and according to the 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.

Given I'm not going to be using the open OS-level file handle given to me, do I need to close it? I understand about regular Python file handles and closing them but I'm not familiar with OS-level file descriptors/handles.

So is this better:

fd, filename = tempfile.mkstemp()
os.close(fd)

Or can I simply just do this:

_, output_filename = tempfile.mkstemp()
Jamie Scott
  • 452
  • 4
  • 20
  • I think you are being confused by the term "OS-level handle". As stated in the quote you attached, this handle is **the same** as would be returned from calling `open()`, so you should treat it exactly the same as a regular file. So, yes, close it. You don't have much to do with the filename. it is just a string. The reason it is returned as well, is because it is a temp file and given an arbitrary name – Tomerikoo Jul 08 '19 at 12:47
  • @Tomerikoo I don't believe that's true. `os.open()` and `open()` are two quite different functions and return two very different things. `os.open` docs say ". Return the file descriptor for the newly opened file." whereas the `open()` docs say "Open file and return a corresponding file object.". So one returns a number, a OS-level file descriptor, and one returns a Python file object. – Jamie Scott Jul 08 '19 at 15:53
  • 1
    This answer could help you with your task. There is some useful info about `tempfile` module. https://stackoverflow.com/a/20912974/841339 – Mauro Baraldi Jul 08 '19 at 15:54
  • @JamieScott sorry for that, I was the one confused... :) – Tomerikoo Jul 09 '19 at 08:15

1 Answers1

2

The returned file descriptor is not a file object, the garbage collector will not close it for you. You should use:

fd, filename = tempfile.mkstemp()
os.close(fd)

The returned file descriptor is useful to avoid race conditions where the filename is replaced with a symbolic link to a file that the attacker can not read but you can which can result in data exposure.

Dan D.
  • 73,243
  • 15
  • 104
  • 123