Created
May 11, 2015 22:40
-
-
Save tueda/28fb15041e54306b664b to your computer and use it in GitHub Desktop.
Making a temporary directory with a context manager.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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