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

发布时间:2023-06-09 09:31:47 人气:135 作者:多测师

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

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

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

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

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

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

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

  1、创建临时文件

  import tempfile

  import os

  # 创建文件

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

  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学习指路:请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线