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