How to get the absolute path of a tempfile.TemporaryFile?

34 Views Asked by At

Is there a way to get the absolute path of a tempfile.TemporaryFile? The name attribute returns integer which seems to be the file descriptor, but would like to get the actual path name.

import tempfile

file = tempfile.TemporaryFile(mode="w", encoding="utf-8")
print(file.name)
-----
56

Looking for a way to get a similar result as below.

file = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8")
print(file.name)
-----
/tmp/tmp6ran0e71
1

There are 1 best solutions below

0
DjaouadNM On

From the documentation for tempfile.TemporaryFile:

tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

Emphasis on "Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created", seeing that you are apparently under a Unix system, tempfile.TemporaryFile will not create or will not maintain a directory entry for the file. This is not the same under some other platforms though (e.g. Windows), where there will be a path even for a tempfile.TemporaryFile (also explained in the docs).