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