python中temp的用法_Python之tempfile模块的使用

tempfile模块的作用

主要是创建临时目录,存放临时数据,关闭时,临时文件则删除处理

1、手动创建临时文件与filetemp模块创建临时文件的比较

ContractedBlock.gif

ExpandedBlockStart.gif

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模块,创建临时文件,并且写入字节数据

ContractedBlock.gif

ExpandedBlockStart.gif

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模块,创建临时文件,并且写一次性写入多行数据

ContractedBlock.gif

ExpandedBlockStart.gif

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、获取临时文件的名字,并且判断关闭后,临时文件是否存在

ContractedBlock.gif

ExpandedBlockStart.gif

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,超出大小则写入硬盘上

ContractedBlock.gif

ExpandedBlockStart.gif

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()函数将缓存数据写入硬盘

ContractedBlock.gif

ExpandedBlockStart.gif

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()打开文件,获取临时文件的路径,并且判断创建临时文件是否存在

ContractedBlock.gif

ExpandedBlockStart.gif

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(后缀)

ContractedBlock.gif

ExpandedBlockStart.gif

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、获取临时文件的目录位置和文件名前临

ContractedBlock.gif

ExpandedBlockStart.gif

importtempfileprint('gettempdir():', tempfile.gettempdir())print('gettemprefix():', tempfile.gettempprefix())

tempfile_settings.py

运行效果

gettempdir(): C:\Users\ADMINI~1\AppData\Local\Temp

gettemprefix(): tmp

10、修 改临时文件的目录

ContractedBlock.gif

ExpandedBlockStart.gif

importtempfile

tempfile.tempdir= 'C:\\'

print('gettempdir()', tempfile.gettempdir())

tempfile_tempdir.py

运行效果

gettempdir() C:\

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值