在Python中获取临时目录的跨平台方法 [英] Cross-platform way of getting temp directory in Python

查看:276
本文介绍了在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:

  1. TMPDIR环境变量命名的目录.
  2. TEMP环境变量命名的目录.
  3. TMP环境变量命名的目录.
  4. 特定于平台的位置:
    • RiscOS 上,由Wimp$ScrapDir环境变量命名的目录.
    • Windows 上,目录C:\TEMPC:\TMP\TEMP\TMP依次排列.
    • 在所有其他平台上,目录/tmp/var/tmp/usr/tmp依次排列.
  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. 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.

这篇关于在Python中获取临时目录的跨平台方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆