TOC

Python tempfile

import tempfile
import time

timestr = time.strftime("%Y%m%d%H%M%S")

临时文件

# tempfile.mktemp(suffix='', prefix='tmp', dir=None)
# tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

filepath_temp = tempfile.mktemp(suffix='.html', prefix='.cache_%s_' % timestr)
print(filepath_temp)
# /tmp/.cache_20210929205452_zlmi3pkf.html

filepath_temp = tempfile.mktemp(suffix='.html', prefix='.cache_%s_' % timestr,
                                dir='/opt/apps/markjour/tmp/')
print(filepath_temp)
# /opt/apps/markjour/tmp/.cache_20210929205452_mcr7nj3e.html

filepath_temp = tempfile.mkstemp(suffix='.html', prefix='.cache_%s_' % timestr, text=True)

mkstempmktemp 的区别:mkstemp 返回一个文件描述符,mktemp 返回一个文件路径。
mktemp 返回的路径理论上会被另一个进程使用,所以这是 UNSAFE 的,应该用 mkstemp 代替。
mktemp 从 Python 2.3 开始标记为 Deprecated,但是至今还是可以调用。

临时目录

# tempfile.mkdtemp(suffix=None, prefix=None, dir=None)
dirpath_temp = tempfile.mkdtemp()
print(dirpath_temp)
# /tmp/tmp1dj2cl0d

dirpath_temp = tempfile.mkdtemp(prefix='build_',
                                dir='/opt/apps/markjour/tmp/')
print(dirpath_temp)
# /opt/apps/markjour/tmp/build_9k5synh5