会自动清除的文件——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: C:\Users\jerry\AppData\Local\Temp\tmpyxnujlq1

从上面运行的结果可以看出,用pf.close()将文件对象关闭后,这个文件就不存在了,并不需要等待运行程序的结束。但是通过文件浏览器可以看到,程序退出后临时文件夹仍然存在的:

但是如果使用with语句创建临时文件夹,with语句结束后,该文件夹则会被自动删除:

with td() as tempdir2:
    print(tempdir2)
    print(tempdir2,'exists status:',os.path.exists(tempdir2))
print(tempdir2,'after with-as exists status:',os.path.exists(tempdir2))    

运行结果:


C:\Users\jerry\AppData\Local\Temp\tmpe3s9ofz7
C:\Users\jerry\AppData\Local\Temp\tmpe3s9ofz7 exists status: True
C:\Users\jerry\AppData\Local\Temp\tmpe3s9ofz7 after with-as exists status: False

前面的内容演示了如何使用tempfile生成临时文件,但是需要注意文件或者文件夹的“生命周期”,如果文件或者文件夹已经被删除再访问它们就会出现报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值