Skip to content

Instantly share code, notes, and snippets.

@freyes
Created June 27, 2013 22:15
Show Gist options
  • Save freyes/5880889 to your computer and use it in GitHub Desktop.
Save freyes/5880889 to your computer and use it in GitHub Desktop.
A context to use temporary directory and don't have to 'remember' to delete it
import os
import tempfile
import shutil
from contextlib import contextmanager
@contextmanager
def mkdtemp(*args, **kwargs):
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shutil.rmtree(d)
with mkdtemp() as tmpdir:
# here we can use a temporary directory that will be removed
assert os.path.isdir(tmpdir)
assert not os.path.isdir(tmpdir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment