Python中跨平台获取临时目录的方法
有没有一种跨平台的方法可以在Python 2.6中获取到temp
目录的路径呢?
比如,在Linux系统中,这个路径是/tmp
,而在XP系统中则是C:\Documents and settings\[user]\Application settings\Temp
。
5 个回答
31
我使用的是:
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'
; 这个路径并不是我总是想要的。
94
这段代码应该能满足你的需求:
print(tempfile.gettempdir())
在我的Windows电脑上,运行后我得到:
c:\temp
而在我的Linux电脑上,我得到:
/tmp
532
这就是 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
这些目录,按这个顺序。- 最后,如果以上都没有找到,就会使用当前的工作目录。