Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
'errors' -- the errors argument to io.open (default None)
The file is created as mkstemp() would do it.
Returns an object with a file-like interface. The file has no
name, and will cease to exist when it is closed.
>>> 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 file using a context manager# close the file, use the name to open the file again
>>> with tempfile.NamedTemporaryFile(delete_on_close=False)as fp:
... fp.write(b'Hello world!')
... fp.close()
... # the file is closed, but not removed
... # open the file again by using its name
... withopen(fp.name, mode='rb')as f:
... f.read()b'Hello world!'
>>>
# file is now 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