Cross-platform way of getting temp directory in Python
PythonCross PlatformTemporary DirectoryPython Problem Overview
Is there a cross-platform way of getting the path to the temp
directory in Python 2.6?
For example, under Linux that would be /tmp
, while under XP C:\Documents and settings\[user]\Application settings\Temp
.
Python Solutions
Solution 1 - Python
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
- The directory named by the
TMPDIR
environment variable. - The directory named by the
TEMP
environment variable. - The directory named by the
TMP
environment variable. - A platform-specific location:
- On RiscOS, the directory named by the
Wimp$ScrapDir
environment variable. - On Windows, the directories
C:\TEMP
,C:\TMP
,\TEMP
, and\TMP
, in that order. - On all other platforms, the directories
/tmp
,/var/tmp
, and/usr/tmp
, in that order.
- On RiscOS, the directory named by the
- As a last resort, the current working directory.
Solution 2 - Python
This should do what you want:
print tempfile.gettempdir()
For me on my Windows box, I get:
c:\temp
and on my Linux box I get:
/tmp
Solution 3 - Python
I use:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
This is because on MacOS, i.e. Darwin, tempfile.gettempdir()
and os.getenv('TMPDIR')
return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
; it is one that I do not always want.
Solution 4 - Python
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
Solution 5 - Python
Why so many complex answers?
I just use this
(os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"