原文链接: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:

最低0.47元/天 解锁文章
627

被折叠的 条评论
为什么被折叠?



