Python:创建临时目录或文件

简介:在程序运行时,有时需要创建临时文件或目录以便使用。在使用后希望将这些文件或目录销毁,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()
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值