在Python中获取临时目录的跨平台方式
发布于 2021-01-29 15:11:56
temp
在Python 2.6中是否有跨平台的方法来获取目录的路径?
例如,在Linux/tmp
下为XP,而在XP下为C:\Documents and settings\[user]\Application
settings\Temp
。
关注者
0
被浏览
46
1 个回答
-
那将是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
在这个顺序。
- 在 RiscOS上 ,
- 不得已时,使用当前工作目录。
- 由