• 会自动清除的文件——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生成临时文件,但是需要注意文件或者文件夹的“生命周期”,如果文件或者文件夹已经被删除再访问它们就会出现报错。

  • 相关阅读:
    Spring中加密工具类DigestUtils和BCryptPasswordEncoder
    个人IPO模式
    __set_current_state
    3dmax渲染内存不足,这样解决!
    redis问题:三种集群——主从、哨兵、cluster集群;16384槽等
    【笔者感悟】笔者的学习感悟【三】
    初阶指针(2)
    面向对象程序设计关于Lua的初识
    【C++】笔试训练(六)
    Git详解及 github与gitlab使用
  • 原文地址:https://blog.csdn.net/juzicode00/article/details/139247990