简介:在程序运行时,有时需要创建临时文件或目录以便使用。在使用后希望将这些文件或目录销毁,tempfile模块中的各种函数可以用来完成这个任务。tempfile 模块专门用于创建临时文件和临时目录,它既可以在 UNIX 平台上运行良好,也可以在 Windows 平台上运行良好。
模块函数与功能:函数参数略
tempfile.TemporaryFile() 创建临时文件。该函数返回一个类文件对象,也就是支持文件 I/O。
tempfile.NamedTemporaryFile() 创建临时文件。该函数的功能与上一个函数的功能大致相同,只是它生成的临时文件在文件系统中有文件名。
tempfile.SpooledTemporaryFile() 创建临时文件。与 TemporaryFile 函数相比,当程序向该临时文件输出数据时,会先输出到内存中,直到超过 max_size 才会真正输出到物理磁盘中。
tempfile.TemporaryDirectory() 生成临时目录。
tempfile.gettempdir() 获取系统的临时目录。
tempfile.gettempdirb() 与 gettempdir() 相同,只是该函数返回字节串。
tempfile.gettempprefix() 返回用于生成临时文件的前缀名。
tempfile.gettempprefixb() 与 gettempprefix() 相同,只是该函数返回字节串。
案例:
# -*- coding: utf-8 -*-
# time: 2023/2/7 0:46
# file: do.py
# 公众号: 玩转测试开发
import os
from tempfile import TemporaryFile, TemporaryDirectory
def create_dir():
with TemporaryDirectory() as dirname:
print("dirname is :", dirname)
result = os.path.exists(dirname)
# 运行处理结果中,在没有退出先,即with内目录仍存在,未关闭,所以文件不存在返回 True
print(f"result:{result}")
# 运行处理结果后, 目录会被自动消除,所以目录不存在,返回 False
print(f"dirname:{dirname}")
result2 = os.path.exists(dirname)
print(f"result2:{result2}")
def create_file():
with TemporaryFile('w+t') as f:
f.write("hello world")
f.write("testing")
f.seek(0)
data = f.read()
print(f"data:{data}")
result = os.path.exists(f.name)
# 运行处理结果中,在没有退出先,即with内文件仍存在,未关闭,所以文件不存在返回 True
print(f"result:{result}")
# 运行处理结果后, 文件会被自动消除,所以文件不存在,返回 False
print(f"f.name:{f.name}")
result2 = os.path.exists(f.name)
print(f"result2:{result2}")
if __name__ == '__main__':
create_dir()
print("*" * 80)
create_file()