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

在 Python 2.6 中是否有跨平台获取 temp 目录路径的方法?

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

最佳答案

那就是 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

为了完整起见,根据文档,这是它搜索临时目录的方式:

  1. TMPDIR 环境变量命名的目录。
  2. TEMP 环境变量命名的目录。
  3. TMP 环境变量命名的目录。
  4. 特定于平台的位置:
    • RiscOS 上,由 Wimp$ScrapDir 环境变量命名的目录。
    • Windows 上,目录 C:\TEMPC:\TMP\TEMP\TMP,按此顺序。
    • 在所有其他平台上,目录 /tmp/var/tmp/usr/tmp 依次排列。
  5. 作为最后的手段,当前工作目录。

https://stackoverflow.com/questions/847850/

相关文章:

python - 从 Numpy 数组 : How do I specify the index c

python - 在 Python 中,如果我在 "with" block 内返回,文件还会关闭吗?

python - 如何检查变量是否是类?

python - 如何逐行读取大型文本文件,而不将它们加载到内存中?

linux - 更改 crontab 文件后重新启动 cron?

linux - Bash 忽略特定命令的错误

linux - 如何递归查找并列出具有子目录和时间的目录中的最新修改文件

python - 为什么 Python 没有符号函数?

linux - ./配置 :/bin/sh^M : bad interpreter

linux - 如何在linux命令行中替换多个文件中的字符串