import os import tempfile print "building a file name yourself:" filename = '/tmp/guess_my_name.%s.txt' % os.getpid() temp = open(filename,'w+b') try: print 'temp:',temp print 'temp.name',temp.name finally: temp.close() os.remove(filename) print "buildint a file using tempfile" t = tempfile.TemporaryFile() try: print 'temp:',temp print 'temp.name',temp.name finally: temp.close()
building a file name yourself: temp: <open file '/tmp/guess_my_name.24462.txt', mode 'w+b' at 0x103567db0> temp.name /tmp/guess_my_name.24462.txt buildint a file using tempfile temp: <closed file '/tmp/guess_my_name.24462.txt', mode 'w+b' at 0x103567db0> temp.name /tmp/guess_my_name.24462.txt
使用tempfile.TemporarFile函数来创建的临时文件,其他的应用程序无法找到或打开这个文件,因为它并没有引用文件系统表。
这个函数创建的临时文件,关闭后自动删除。
=============
tempfile.TemporarFile默认情况下使用w+b权限来创建文件;
使用temp.seek来重定位,方便以后读取数据
import os import tempfile temp = tempfile.TemporaryFile() try: temp.write('some data') temp.seek(0) print temp.read() finally: temp.close()
===========