platform way of getting temp directory in Python
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 settingsTemp
.
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:
TMPDIR
environment variable. TEMP
environment variable. TMP
environment variable. Wimp$ScrapDir
environment variable. C:TEMP
, C:TMP
, TEMP
, and TMP
, in that order. /tmp
, /var/tmp
, and /usr/tmp
, in that order. 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
I use:
import platform
import tempfile
tempdir = '/tmp' if platform.system() == 'Darwin' else tempfile.gettempdir()
This is because on MacOS, ie 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 want!
上一篇: 跨平台修补
下一篇: 在Python中获取临时目录的平台方式