tempfile模块用于创建临时目录和临时文件。

tempfile.TemporaryFile():创建临时文件,不指定文件名,文件关闭即删除临时文件。默认mode='w+b'二进制形式,可通过mode='w+t'改为text形式

tempfile.mkdtemp():创建临时目录,返回目录路径,需要手动删除临时目录

tempfile.mkstemp():创建临时文件,返回(安全级别,目录路径)元组,需要手动删除临时文件

tempfile.mktemp():返回临时文件的路径,但不创建该临时文件

tempfile.gettempdir():返回创建临时文件的文件夹路径

#!/usr/bin/env python
import os
import tempfile

def createFile1():          #creat tempfile by yourself
    print "Building a file name yourself:"
    filename='/tmp/file.%s.txt' % os.getpid()
    os.listdir('/tmp')
    temp=open(filename,'w+b')
    os.listdir('/tmp')
    try:
        print "temp:",temp
        print "temp.name:",temp.name
    finally:
        temp.close()
        os.remove(filename)     #remove tempfile by yourself

def createFile2():              #create tempfile use tempfile method
    print "TemporaryFile:"
    os.listdir('/tmp')
    temp=tempfile.TemporaryFile()
    os.listdir('/tmp')
    try:
        print 'temp:',temp
        print 'temp.name:',temp.name
    finally:
        temp.close()            #once close file,the tempfile is removed

def wrTempfile1():                  #write and read binary file
    temp=tempfile.TemporaryFile()   #default mode='w+b'
    try:
        temp.write("binary data")
        temp.seek(0)                #locate the begin position of file
        print temp.read()
    finally:
        temp.close()                #close and remove temp file

def wrTempfile2():                  #write and read text file
    temp=tempfile.TemporaryFile(mode='w+t') #change mode='w+t'
    try:
        temp.writelines(["text data1\n","text data2\n"])
        temp.seek(0)
        for line in temp:
            print line.strip()
    finally:
        temp.close()
def mkTempdir():
    directory_name=tempfile.mkdtemp()
    print directory_name
    os.removedirs(directory_name)       #clean up directory by yourself
def mkTempfile():
    file_name=tempfile.mkstemp()
    print file_name
    os.remove(file_name[1])

if __name__=='__main__':
    createFile1()
    createFile2()
    wrTempfile1()
    wrTempfile2()
    mkTempdir()
    mkTempfile()