In Python, how to get the default temporary directory?

Asked

Viewed 821 times

7

I am making a program that uses a temporary file to save a serialized object (pickled). At the moment, the program is generating in the /tmp, but this path is specific to Unix/Linux; wanted to take the path of the default temporary operating system directory that the program runs.

In Java, I know you can do it with System.getProperty("java.io.tmpdir"). What is the equivalent way to do this in Python?

2 answers

12


tempfile.gettempdir() returns the directory used as a temporary directory.

import tempfile

print tempfile.gettempdir()
  • good, that was it. =)

6

The Talles answer is technically correct, but the ideal is to use tempfile.TemporaryFile or tempfile.NamedTemporaryFile to create the temporary file instead of concatenating the tempfile.gettempdir() with a constant name, so you ensure the uniqueness of the file name avoiding that another file with the same name is created by another thread, process or user.

import tempfile

tmp = tempfile.NamedTemporaryFile(delete=False) # pra não ser excluído qdo fizer close()
tmp.write("conteúdo do arquivo")
tmp.close()
  • 1

    Hmm, but this solution assumes that the temporary file has shorter life than running the application. In this case, this would really be the best way. But in my case I need a temporary file with a predictable name, because the application will reuse if it restarts -- however it does not need to survive OS Restart. That’s why I explicitly wanted the temporary directory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.