在Python 2.6中是否有跨平台的方法获取临时目录的路径?

例如,在Linux下是/tmp,而在XP下是C:\Documents and settings\[user]\Application settings\Temp。


这就是tempfile模块。

它有获取临时目录的函数,也有一些快捷方式在其中创建临时文件和目录,可以是有名称的,也可以是未命名的。

例子:

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

为了完整起见,下面是它如何搜索临时目录,根据文档:

由TMPDIR环境变量命名的目录。 由TEMP环境变量命名的目录。 由TMP环境变量命名的目录。 特定于平台的位置: 在RiscOS上,由Wimp$ScrapDir环境变量命名的目录。 在Windows上,目录C:\TEMP、C:\TMP、\TEMP和\TMP按此顺序排列。 在所有其他平台上,目录/tmp、/var/tmp和/usr/tmp按此顺序排列。 作为最后的手段,当前工作目录。

这应该是你想要的:

print(tempfile.gettempdir())

对我来说,在我的Windows盒子上,我得到:

c:\temp

在我的Linux盒子上,我得到:

/tmp

基于@nosklo的评论和回答,最简单的方法是:

import tempfile
tmp = tempfile.mkdtemp()

但是如果你想手动控制目录的创建:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

这样,当你用完(隐私、资源、安全等)后,你可以很容易地清理自己:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

这类似于谷歌Chrome和Linux systemd这样的应用程序。他们只是使用更短的十六进制散列和特定于应用程序的前缀来“宣传”他们的存在。

我使用:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

这是因为在MacOS上,即Darwin, tempfile.gettempdir()和os.getenv('TMPDIR')返回的值是'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T';这不是我一直想要的。

为什么有这么多复杂的答案?

我只用这个

   (os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"