Python tempfile - zhongjiajie/zhongjiajie.github.com GitHub Wiki
最常用的方法,生成一个有名称的临时文件
import tempfile
# create a temporary file and write some data to it
fp = tempfile.TemporaryFile()
fp.write(b'Hello world!')
# read data from file
fp.seek(0)
fp.read()
b'Hello world!'
# close the file, it will be removed
fp.close()
# create a temporary file using a context manager
with tempfile.TemporaryFile() as fp:
fp.write(b'Hello world!')
fp.seek(0)
fp.read()
# b'Hello world!'
# file is now closed and removed
- 不删除临时文件的方法
tempfile.NamedTemporaryFile
默认在使用完了后会将临时文件删除,可以通过调整参数实现不删除文件
f = tempfile.NamedTemporaryFile(delete=False)
f.name
f.write(b"Hello World!\n")
f.close()
os.path.exists(f.name) # True
os.unlink(f.name)
os.path.exists(f.name) # False
有名称的临时文件夹,New in version 3.2
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
如果想要在python3.2之前使用临时文件夹的功能,可以自己用上下文管理器写一个
import errno
import shutil
from tempfile import mkdtemp
from contextlib import contextmanager
@contextmanager
def TemporaryDirectory(suffix='', prefix=None, dir=None):
name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
try:
yield name
finally:
try:
shutil.rmtree(name)
except OSError as e:
# ENOENT - no such file or directory
if e.errno != errno.ENOENT:
raise e
获取系统的临时目录路径tempfile.gettempdir()