os.chdir(os.path.expanduser(newdir))
try:
    yield
finally:
    os.chdir(prevdir)
cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()

def cleanup():
    shutil.rmtree(dirpath)
how to create a temporary directory and get the path / file name in python