首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中获取临时目录的跨平台方法

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

Stack Overflow用户
提问于 2009-05-11 12:21:46
回答 4查看 148.2K关注 0票数 320

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

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

EN

回答 4

Stack Overflow用户

发布于 2009-05-11 12:27:31

这应该是您想要的结果:

print tempfile.gettempdir()

对于我在我的Windows机器上,我得到:

c:\temp

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

/tmp
票数 72
EN

Stack Overflow用户

发布于 2017-04-15 03:51:38

我使用:

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

票数 23
EN

Stack Overflow用户

发布于 2016-05-11 04:04:21

最简单的方法,基于@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)

这类似于谷歌浏览器和Linux systemd等应用程序所做的事情。他们只是使用更短的十六进制哈希和应用程序特定的前缀来“广告”他们的存在。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/847850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档