Skip to content

Instantly share code, notes, and snippets.

@tueda
Created May 11, 2015 22:40
Show Gist options
  • Select an option

  • Save tueda/28fb15041e54306b664b to your computer and use it in GitHub Desktop.

Select an option

Save tueda/28fb15041e54306b664b to your computer and use it in GitHub Desktop.
Making a temporary directory with a context manager.
import contextlib
import datetime
import tempfile
import shutil
@contextlib.contextmanager
def make_temp_dir(prefix=""):
"A context manager for a temporary directory."
if prefix:
prefix += "."
prefix += datetime.datetime.now().strftime("%Y%m%d%H%M%S.")
temp_dir = tempfile.mkdtemp(prefix=prefix)
yield temp_dir
shutil.rmtree(temp_dir)
if __name__ == '__main__':
with make_temp_dir() as tmpdir:
print(tmpdir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment