_tempfile.py 760 B

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