Python中获取临时目录的跨平台方法

2024-06-07 01:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 2.6中,有没有一种跨平台的方法来获取temp目录的路径?

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


Tags: and方法路径目录settingsapplicationlinux跨平台
3条回答

那就是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

为了完整起见,下面是根据文档搜索临时目录的方法:

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

这应该符合您的要求:

print tempfile.gettempdir()

在我的窗口框上,我得到:

c:\temp

在我的Linux机器上,我得到:

/tmp

我使用:

import platform
import tempfile

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

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

相关问题 更多 >