在 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
为了完整起见,根据文档,这是它搜索临时目录的方式:
TMPDIR
环境变量命名的目录。TEMP
环境变量命名的目录。TMP
环境变量命名的目录。Wimp$ScrapDir
环境变量命名的目录。C:\TEMP
、C:\TMP
、\TEMP
和\TMP
,按此顺序。/tmp
、/var/tmp
和 /usr/tmp
依次排列。https://stackoverflow.com/questions/847850/