fd, name = tempfile.mkstemp 建立临时文件,而且将文件打开python
>>> import tempfile >>> tempfile.mkstemp() (3, '/tmp/tmpkgWSR1')
查看/tmp目录,看到已经生成了真实的文件shell
lsof查询打开的临时文件spa
[wyq@localhost tmp]$ lsof|grep tmp|grep python python 8095 wyq 3u REG 0,33 0 254593 /tmp/tmpkgWSR1
发现mkstemp不只建立文件,并且将文件打开. 使用mkstemp很容易忘了这点,最终形成OSError: [Errno 24] Too many open files错误.code
mkstemp返回的是文件描述和文件路径,并不经常使用,经常使用的是下面两个.对象
mktemp
内存
name = tempfile.mktemp 返回一个临时文件的路径,但并不建立该临时文件it
>>> import tempfile >>> tempfile.mktemp() '/tmp/tmpPVidBM'
仅仅生成临时文件名class
tempfile.TemporaryFile 返回文件对象(file-like)用于临时数据保存。当文件对象被close或者被del的时候,临时文件将从磁盘上删除import
import time with tempfile.TemporaryFile(mode='w+r') as f: f.write("=============") f.seek(0) print f.read() time.sleep(10)
TemporaryFile并未在/tmp目录中建立临时文件,应该只存在与内存中.file