Python之tempfile模块的使用
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))
运行效果
创建一个PID的文件名 temp: <_io.BufferedRandom name='temp/guess_my_name.47904.txt'> temp.name: 'temp/guess_my_name.47904.txt' TemporaryFile: temp: <tempfile._TemporaryFileWrapper object at 0x000001FFFC0F7808> temp.name 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmpgtqnvju1' Process finished with exit code 0
2、使用tempfile模块,创建临时文件,并且写入字节数据
import tempfile with tempfile.TemporaryFile() as temp: temp.write(b'Some Data') temp.seek(0) print(temp.read())
运行效果
b'Some Data'
3、使用tempfile模块,创建临时文件,并且写一次性写入多行数据
import tempfile with tempfile.TemporaryFile(mode='w+t') as f: f.writelines(['first\n', 'second\n']) f.seek(0) for line in f: print(line.rstrip())
运行效果
first
second
4、获取临时文件的名字,并且判断关闭后,临时文件是否存在
import pathlib import tempfile with tempfile.NamedTemporaryFile() as temp: print('temp:') print(' {!r}'.format(temp)) print(' {!r}'.format(temp.name)) f = pathlib.Path(temp.name) print('关闭文件后,判断文件是否存在', f.exists())
运行效果
temp: <tempfile._TemporaryFileWrapper object at 0x000001E03F57E788> 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp7ryldveg' 关闭文件后,判断文件是否存在 False
5、使用 SpooledTemporaryFile 在设置大小内,将数据存到BytesIO or StringIO,超出大小则写入硬盘上
import tempfile 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)
运行效果
temp: <tempfile.SpooledTemporaryFile object at 0x000001EB82E0E8C8>
False <_io.TextIOWrapper encoding='utf-8'> # 这里表示数据写入缓存 False <_io.TextIOWrapper encoding='utf-8'> # 这里表示数据写入缓存
True <tempfile._TemporaryFileWrapper object at 0x000001EB830C7748>
6、 使用 SpooledTemporaryFile 在设置大小内,将数据存到BytesIO or StringIO, 执行rollover()函数将缓存数据写入硬盘
import tempfile 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)
运行效果
temp: <tempfile.SpooledTemporaryFile object at 0x000002AE7DC2E988> False <_io.TextIOWrapper encoding='utf-8'> False <_io.TextIOWrapper encoding='utf-8'> False <_io.TextIOWrapper encoding='utf-8'> rolling over True <tempfile._TemporaryFileWrapper object at 0x000002AE7DEE7508> Process finished with exit code 0
7、使用TemporaryDirectory()打开文件,获取临时文件的路径,并且判断创建临时文件是否存在
import tempfile import pathlib 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('*')))
运行效果
C:\Users\ADMINI~1\AppData\Local\Temp\tmpr2bs24eg
Directory exists after? False
Content after: []
8、自定义临时文件名,格式为:dir(目录)+ prefix(前缀) + random(随机生成) + suffix(后缀)
import tempfile with tempfile.NamedTemporaryFile(suffix='_suffix', prefix='prefix_', dir='C:\\') as temp: print('temp:') print(' ', temp) print('temp.name:') print(' ', temp.name)
运行效果
temp: <tempfile._TemporaryFileWrapper object at 0x000001D416DBEB48> temp.name: C:\prefix_rhr6yeop_suffix
9、获取临时文件的目录位置和文件名前临
import tempfile print('gettempdir():', tempfile.gettempdir()) print('gettemprefix():', tempfile.gettempprefix())
运行效果
gettempdir(): C:\Users\ADMINI~1\AppData\Local\Temp
gettemprefix(): tmp
10、修 改临时文件的目录
import tempfile tempfile.tempdir = 'C:\\' print('gettempdir()', tempfile.gettempdir())
运行效果
gettempdir() C:\