tempfile模块的作用
主要是创建临时目录,存放临时数据,关闭时,临时文件则删除处理
1、手动创建临时文件与filetemp模块创建临时文件的比较
import os import tempfile print('创建一个PID的文件名') filename = 'temp/guess_my_name.{}.txt'.format(os.getpid()) # 手动创建临时文件,并且获取文件名 with open(filename, 'w+b') as temp: print('temp:') print(' {!r}'.format(temp)) print('temp.name:') print(' {!r}'.format(temp.name)) os.remove(filename) # 利用tempfile模块创建临时文件,并且获取文件名 print('\nTemporaryFile:') with tempfile.TemporaryFile() as temp: print('temp:') print(' {!r}'.format(temp)) print('temp.name') print(' {!r}'.format(temp.name))