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

问题描述 投票:0回答:5

是否有跨平台的方法来获取Python 2.6中

temp
目录的路径?

例如,在 Linux 下为

/tmp
,而在 XP 下为
C:\Documents and settings\[user]\Application settings\Temp

python cross-platform temporary-directory
5个回答
522
投票

这将是 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:\TEMP
      C:\TMP
      \TEMP
      \TMP
    • 在所有其他平台上,目录按顺序为
      /tmp
      /var/tmp
      /usr/tmp
  5. 作为最后的手段,当前工作目录。

93
投票

这应该可以满足你的要求:

print(tempfile.gettempdir())

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

c:\temp

在我的 Linux 机器上我得到:

/tmp

30
投票

我用:

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'
;这是我并不总是想要的。


26
投票

最简单的方法,基于@nosklo的评论和answer

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)

这类似于 Google Chrome 和 Linux

systemd
等应用程序的用途。他们只是使用更短的十六进制哈希和特定于应用程序的前缀来“宣传”他们的存在。


-6
投票

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

我就用这个

   (os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"
© www.soinside.com 2019 - 2024. All rights reserved.