1from tempfile import NamedTemporaryFile
2from contextlib import contextmanager
3import os
4
5@contextmanager
6def temporary_file(suffix=''):
7    """Yield a writeable temporary filename that is deleted on context exit.
8
9    Parameters
10    ----------
11    suffix : string, optional
12        The suffix for the file.
13
14    Examples
15    --------
16    >>> import numpy as np
17    >>> from skimage import io
18    >>> with temporary_file('.tif') as tempfile:
19    ...     im = np.arange(25, dtype=np.uint8).reshape((5, 5))
20    ...     io.imsave(tempfile, im)
21    ...     assert np.all(io.imread(tempfile) == im)
22    """
23    tempfile_stream = NamedTemporaryFile(suffix=suffix, delete=False)
24    tempfile = tempfile_stream.name
25    tempfile_stream.close()
26    yield tempfile
27    os.remove(tempfile)
28