在Python中获取临时目录的跨平台方法 [英] Cross-platform way of getting temp directory in Python
本文介绍了在Python中获取临时目录的跨平台方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有跨平台的方法来获取Python 2.6中 temp
目录的路径?
Is there a cross-platform way of getting the path to the temp
directory in Python 2.6?
例如,在Linux下为/tmp
,而在XP下为C:\Documents and settings\[user]\Application settings\Temp
.
For example, under Linux that would be /tmp
, while under XP C:\Documents and settings\[user]\Application settings\Temp
.
推荐答案
那将是 tempfile 模块.
它具有获取临时目录的功能,还具有一些在其中创建命名或未命名临时文件和目录的快捷方式.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
示例:
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
为完整起见,根据文档,这是它搜索临时目录的方式:
For completeness, here's how it searches for the temporary directory, according to the documentation:
- 由
TMPDIR
环境变量命名的目录. - 由
TEMP
环境变量命名的目录. - 由
TMP
环境变量命名的目录. - 特定于平台的位置:
- 在 RiscOS 上,由
Wimp$ScrapDir
环境变量命名的目录. - 在 Windows 上,目录
C:\TEMP
,C:\TMP
,\TEMP
和\TMP
依次排列. - 在所有其他平台上,目录
/tmp
,/var/tmp
和/usr/tmp
依次排列.
- 在 RiscOS 上,由
- The directory named by the
TMPDIR
environment variable. - The directory named by the
TEMP
environment variable. - The directory named by the
TMP
environment variable. - A platform-specific location:
- On RiscOS, the directory named by the
Wimp$ScrapDir
environment variable. - On Windows, the directories
C:\TEMP
,C:\TMP
,\TEMP
, and\TMP
, in that order. - On all other platforms, the directories
/tmp
,/var/tmp
, and/usr/tmp
, in that order.
- On RiscOS, the directory named by the
这篇关于在Python中获取临时目录的跨平台方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文