python中创建临时文件夹

来源:互联网 发布:数据网关 编辑:程序博客网 时间:2024/04/28 20:53


This module creates temporary files and directories. It works on all supported platforms.TemporaryFile,NamedTemporaryFile,TemporaryDirectory, andSpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.mkstemp() andmkdtemp() are lower-level functions which require manual cleanup.


Here are some examples of typical usage of the tempfile module:

>>>
>>> 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# create a temporary directory using the context manager>>> with tempfile.TemporaryDirectory() as tmpdirname:...     print('created temporary directory', tmpdirname)>>># directory and contents have been removed
0 0
原创粉丝点击