【笔记】Python3临时文件和临时目录

前言

Python3利用tempfile模块对临时文件和临时目录进行操作

引入模块

1
import tempfile

创建临时目录

1
2
with TemporaryDirectory() as temp_dir:
print(temp_dir)

创建临时文件

  • TemporaryFile的默认模式为二进制读写,如果需要实现文本的读写,需要重新指定模式
  • TemporaryFile的中delete属性默认值是True,表示临时文件在使用完会自动删除,如果不想自动删除,可以改为False
1
2
3
4
5
6
7
with TemporaryFile(mode="w+") as temp_file:
# 写入一个文件
temp_file.write("<text>")
# 将光标移到起始位置
temp_file.seek(0)
# 读取所有内容
print(temp_file.read())

完成

参考文献

哔哩哔哩——千锋教育