Python进阶教程m4b–临时文件或目录~tempfile

tempfile模块用来生成临时文件或者文件夹,关闭文件对象后,临时文件会被自动删除,程序退出时临时文件夹不会自动删除。

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

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

with td() as tempdir2:
    print(tempdir2)
    print(tempdir2,'exists status:',os.path.exists(tempdir2))
print(tempdir2,'after with-case 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-case exists status: False

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注