• 技术文章 >Python技术 >Python基础教程

    python如何使用TemporaryFile()方法创建临时文件?

    宋雪维宋雪维2021-03-01 14:50:57原创4478

    我们在编程中,会是时不时的创建临时文件,这是因为临时文件不用命名,关闭后会自动被删除,很方便的帮助我们存储临时文件,只需通过对象来访问查找使用。本文介绍python中使用TemporaryFile()方法创建临时文件的过程。

    一、Python创建临时文件方法tempfile.TemporaryFile()

    创建的临时文件,关闭后会自动删除。

    该方法返回一个类文件对象,用于临时数据保存(实际上对应磁盘上的一个临时文件)。

    生成的对象可以用作上下文管理器。完成文件对象的上下文或销毁后(文件对象被 close 或者被 del),临时文件将从文件系统中删除。

    二、python使用TemporaryFile()方法创建临时文件步骤

    1、创建临时文件

    import tempfile
    
    import os
    
    # 创建文件
    file = tempfile.TemporaryFile(mode="w+")
    print(file.name)
    # 4
    
    print(os.path.exists(file.name))
    # True

    2、写入、读取文件

    file.write("hello world")
    
    file.seek(0)
    print(file.read())
    # hello world

    3、关闭文件(这里会把临时文件删除)

    file.close()
    
    print(os.path.exists(file.name))
    # False

    以上就是python中使用TemporaryFile创建的临时文件过程,需要注意的是创建的临时文件不能通过文件系统路径找到,只能用对象来访问哦~python培训相关知识可以点击进行了解。

    专题推荐:python基础
    品易云
    上一篇:python中shell的调用 下一篇:python中如何创建带有文件名的临时文件?

    相关文章推荐

    • python中Pywin32库如何使用?• python中temp是什么意思?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网