• 会自动清除的文件——tempfile


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

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

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

    1. import tempfile
    2. from tempfile import TemporaryDirectory as td
    3. from tempfile import NamedTemporaryFile as ntf
    4. import os
    5. pf = ntf()
    6. tempfn = pf.name
    7. print('filename:',tempfn)
    8. print(tempfn,'exists status:',os.path.exists(tempfn))
    9. pf.close()
    10. print(tempfn,'exists status:',os.path.exists(tempfn)) #文件对象关闭后文件被删除了
    11. print()
    12. tempdir = td()
    13. dirname=tempdir.name
    14. print('dirctory:',dirname)

    运行结果:

    1. filename: C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj
    2. C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj exists status: True
    3. C:\Users\jerry\AppData\Local\Temp\tmpdxdl2xvj exists status: False
    4. dirctory: C:\Users\jerry\AppData\Local\Temp\tmpyxnujlq1

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

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

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

    运行结果:

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

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

  • 相关阅读:
    windows上给oracle打补丁注意事项
    map格式和string格式转化为json格式
    【CTF】AWDP总结(Web)
    腾讯云部署K8s集群
    罗尔中值定理习题
    HBase学习笔记(3)—— HBase整合Phoenix
    某头部证券机构云化与信创双转型深度解析|信创专题
    (黑马出品_05)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
    力扣376. 摆动序列错误用例
    find 命令这 7 种高级用法,你知道多少
  • 原文地址:https://blog.csdn.net/juzicode00/article/details/139247990