Python之tempfile模块的使⽤ tempfile模块的作⽤
主要是创建临时⽬录,存放临时数据,关闭时,临时⽂件则删除处理
1、⼿动创建临时⽂件与filetemp模块创建临时⽂件的⽐较
import os
import tempfile
print('创建⼀个PID的⽂件名')
filename = 'temp/guess_my_name.{}.txt'.pid())
# ⼿动创建临时⽂件,并且获取⽂件名
with open(filename, 'w+b') as temp:
print('temp:')
print(' {!r}'.format(temp))
print('temp.name:')
print(' {!r}'.format(temp.name))
# 利⽤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_'>
temp.name:
'temp/guess_my_'
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)
ad())
tempfile_TemporaryFile_binary.py
运⾏效果
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())
tempfile_TemporaryFile_text.py
运⾏效果
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())
tempfile_NamedTemporaryFile.py
运⾏效果
writelines在python中的用法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)
tempfile_SpooledTemporaryFile.py
运⾏效果
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')
print(temp._rolled, temp._file)
tempfile_SpooledTemporaryFile_explicit.py
运⾏效果
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.write_text('This file is deleted.')
print('Directory exists after?', ists())
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(后缀)import tempfile
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:
<tempfile._TemporaryFileWrapper object at 0x000001D416DBEB48>
temp.name:
C:\prefix_rhr6yeop_suffix
9、获取临时⽂件的⽬录位置和⽂件名前临
import tempfile
print('gettempdir():', pdir())
print('gettemprefix():', pprefix())
tempfile_settings.py
运⾏效果
gettempdir(): C:\Users\ADMINI~1\AppData\Local\Temp
gettemprefix(): tmp
10、修改临时⽂件的⽬录
import tempfile
print('gettempdir()', pdir())
tempfile_tempdir.py
运⾏效果
gettempdir() C:\
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论