zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python编程:tempfile创建临时文件

Python编程 创建 临时文件
2023-09-14 09:07:15 时间

tempfile需要的时候创建零时文件,关闭之后就被删除了

import tempfile

import os

# 创建文件
file = tempfile.TemporaryFile(mode="w+")
print(file.name)
# 4

print(os.path.exists(file.name))
# True

# 写入、读取操作
file.write("hello world")

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

# 关闭资源
file.close()

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

参考: https://docs.python.org/3/library/tempfile.html