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)
'delete' -- whether the file is automatically deleted (default True).
'delete_on_close' -- if 'delete', whether the file is deleted on close
(default True) or otherwise either on context manager exit
(if context manager was used) or on object finalization. .
'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 name of the file
is accessible as its 'name' attribute. The file will be automatically
deleted when it is closed unless the 'delete' argument is set to False.
On POSIX, NamedTemporaryFiles cannot be automatically deleted if
the creating process is terminated abruptly with a SIGKILL signal.
Windows can delete the file even in this case.
>>> 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