tempfile模块的作用
主要是创建临时目录,存放临时数据,关闭时,临时文件则删除处理
1、手动创建临时文件与filetemp模块创建临时文件的比较
importosimporttempfileprint('创建一个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))
tempfile_TemporaryFile.py
运行效果
创建一个PID的文件名
temp:<_io.BufferedRandom name='temp/guess_my_name.47904.txt'>temp.name:'temp/guess_my_name.47904.txt'TemporaryFile:
temp:temp.name'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmpgtqnvju1'Process finished with exit code 0
2、使用tempfile模块,创建临时文件,并且写入字节数据
importtempfile
with tempfile.TemporaryFile() as temp:
temp.write(b'Some Data')
temp.seek(0)print(temp.read())
tempfile_TemporaryFile_binary.py
运行效果
b'Some Data'
3、使用tempfile模块,创建临时文件,并且写一次性写入多行数据
importtempfile
with tempfile.TemporaryFile(mode='w+t') as f:
f.writelines(['first\n', 'second\n'])
f.seek(0)for line inf:print(line.rstrip())
tempfile_TemporaryFile_text.py
运行效果
first
second
4、获取临时文件的名字,并且判断关闭后,临时文件是否存在
importpathlibimporttempfile
with tempfile.NamedTemporaryFile() as temp:print('temp:')print('{!r}'.format(temp))print('{!r}'.format(temp.name))
f=pathlib.Path(temp.name)print('关闭文件后,判断文件是否存在', f.exists())
tempfile_NamedTemporaryFile.py
运行效果
temp:
'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp7ryldveg'关闭文件后,判断文件是否存在 False
5、使用 SpooledTemporaryFile 在设置大小内,将数据存到BytesIO or StringIO,超出大小则写入硬盘上
importtempfile
with tempfile.SpooledTemporaryFile(max_size=100,
mode='w+t',
encoding='utf-8') as temp:print('temp: {!r}'.format(temp))for i in range(3):
temp.write('This line is repeated over and over.\n')print(temp._rolled, temp._file)
tempfile_SpooledTemporaryFile.py
运行效果
temp:
False<_io.TextIOWrapper encoding='utf-8'> # 这里表示数据写入缓存False<_io.TextIOWrapper encoding='utf-8'> # 这里表示数据写入缓存
True
6、 使用 SpooledTemporaryFile 在设置大小内,将数据存到BytesIO or StringIO, 执行rollover()函数将缓存数据写入硬盘
importtempfile
with tempfile.SpooledTemporaryFile(max_size=1000,
mode='w+t',
encoding='utf-8') as temp:print('temp: {!r}'.format(temp))for i in range(3):
temp.write('This line is repeated over and over.\n')print(temp._rolled, temp._file)print('rolling over')
temp.rollover()print(temp._rolled, temp._file)
tempfile_SpooledTemporaryFile_explicit.py
运行效果
temp: False<_io.TextIOWrapper encoding='utf-8'>False<_io.TextIOWrapper encoding='utf-8'>False<_io.TextIOWrapper encoding='utf-8'>rolling over
TrueProcess finished with exit code 0
7、使用TemporaryDirectory()打开文件,获取临时文件的路径,并且判断创建临时文件是否存在
importtempfileimportpathlib
with tempfile.TemporaryDirectory() as directory_name:
the_dir=pathlib.Path(directory_name)print(the_dir)
a_file= the_dir / 'a_file.txt'a_file.write_text('This file is deleted.')print('Directory exists after?', the_dir.exists())print('Content after:', list(the_dir.glob('*')))
tempfile_TemporaryDirectory.py
运行效果
C:\Users\ADMINI~1\AppData\Local\Temp\tmpr2bs24eg
Directory exists after? False
Content after: []
8、自定义临时文件名,格式为:dir(目录)+ prefix(前缀) + random(随机生成) + suffix(后缀)
importtempfile
with tempfile.NamedTemporaryFile(suffix='_suffix',
prefix='prefix_',
dir='C:\\') as temp:print('temp:')print(' ', temp)print('temp.name:')print(' ', temp.name)
tempfile_NamedTemporaryFile_args.py
运行效果
temp:temp.name:
C:\prefix_rhr6yeop_suffix
9、获取临时文件的目录位置和文件名前临
importtempfileprint('gettempdir():', tempfile.gettempdir())print('gettemprefix():', tempfile.gettempprefix())
tempfile_settings.py
运行效果
gettempdir(): C:\Users\ADMINI~1\AppData\Local\Temp
gettemprefix(): tmp
10、修 改临时文件的目录
importtempfile
tempfile.tempdir= 'C:\\'
print('gettempdir()', tempfile.gettempdir())
tempfile_tempdir.py
运行效果
gettempdir() C:\