- contextlib
- contextmanager
- tempfile
- mkdtemp
tempdir context manager
examples/advanced/mytmpdir.py
import os from contextlib import contextmanager import tempfile import shutil @contextmanager def tmpdir(): dd = tempfile.mkdtemp() try: yield dd finally: shutil.rmtree(dd)
examples/advanced/use_mytmpdir.py
from mytmpdir import tmpdir import os with tmpdir() as temp_dir: print(temp_dir) with open( os.path.join(temp_dir, 'some.txt'), 'w') as fh: fh.write("hello") print(os.path.exists(temp_dir)) print(os.listdir(temp_dir)) print(os.path.exists(temp_dir))
/tmp/tmprpuywa3_ True ['some.txt'] False