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

Is there a cross-platform way of getting the path to the temp directory in Python 2.6?

For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp.

解决方案

That would be the tempfile module.

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.

Example:

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:

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.

As a last resort, the current working directory.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值