会自动清除的文件——tempfile

原文链接:http://www.juzicode.com/python-tutorial-tempfile/

在某些不需要持久保存文件的场景下,可以用tempfile模块生成临时文件或者文件夹,这些临时文件或者文件夹在使用完之后就会自动删除。

NamedTemporaryFile用来创建临时文件,TemporaryDirectory用来创建临时文件夹,下面的例子演示了如何创建临时文件和文件夹的基本用法:

import tempfile
from tempfile import TemporaryDirectory as td
from tempfile import NamedTemporaryFile as ntf
import os

pf = ntf()
tempfn = pf.name
print('filename:',tempfn)
print(tempfn,'exists status:',os.path.exists(tempfn))
pf.close()
print(tempfn,'exists status:',os.path.exists(tempfn)) #文件对象关闭后文件被删除了

print()
tempdir = td()
dirname=tempdir.name
print('dirctory:',dirname)

运行结果:


filename: C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj
C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj exists status: True
C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj exists status: False

dirctory:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值