In Python, how do I get the default temporary directory?

6

I'm doing a program that uses a temporary file to save a serialized (pickled) object. Currently, the program is generating in /tmp , but this path is specific to Unix / Linux; wanted to take the path of the default operating system temporary directory that the program will run.

In Java, I know you can do with System.getProperty("java.io.tmpdir") . What's the equivalent way of doing this in Python?

    
asked by anonymous 12.12.2013 / 19:58

2 answers

11

tempfile.gettempdir () returns you the directory used as a temporary directory. / p>

import tempfile

print tempfile.gettempdir()
    
12.12.2013 / 20:02
6

The talles response is technically correct, but it is best to use tempfile.TemporaryFile or tempfile.NamedTemporaryFile to create the temporary file instead of concatenating tempfile.gettempdir() with a constant name, so you guarantee the uniqueness of the file name preventing another file with the same name from being 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()
    
12.12.2013 / 20:29