Mercurial > hg > Lemuriformes
comparison lemuriformes/path.py @ 16:9b1bb9eee962
misc functions related to filesystem paths
| author | Jeff Hammel <k0scist@gmail.com> |
|---|---|
| date | Sun, 10 Dec 2017 17:19:30 -0800 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 15:0d1b8bb1d97b | 16:9b1bb9eee962 |
|---|---|
| 1 """ | |
| 2 functions related to paths | |
| 3 """ | |
| 4 | |
| 5 import shutil | |
| 6 import tempfile | |
| 7 | |
| 8 | |
| 9 def ensure_dir(path): | |
| 10 """ensures `path` is a directory""" | |
| 11 | |
| 12 if os.path.exists(path): | |
| 13 assert os.path.isdir(path) | |
| 14 else: | |
| 15 os.makedirs(path) | |
| 16 return path | |
| 17 | |
| 18 | |
| 19 class TempDir(object): | |
| 20 """temporary directory context manager""" | |
| 21 # For inspiration see | |
| 22 # https://stackoverflow.com/questions/19296146/tempfile-temporarydirectory-context-manager-in-python-2-7 | |
| 23 | |
| 24 def __init__(self): | |
| 25 self.tmpdir = None | |
| 26 | |
| 27 def __enter__(self): | |
| 28 self.tmpdir = tempfile.mkdtemp() | |
| 29 return self.tmpdir | |
| 30 | |
| 31 def __exit__(self, *args): | |
| 32 if not self.tmpdir: | |
| 33 return | |
| 34 shutil.rmtree(self.tmpdir, ignore_errors=True) | |
| 35 self.tmpdir = None |
