Mercurial > hg > Lemuriformes
changeset 16:9b1bb9eee962
misc functions related to filesystem paths
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sun, 10 Dec 2017 17:19:30 -0800 |
parents | 0d1b8bb1d97b |
children | 4793f99b73e0 |
files | lemuriformes/path.py |
diffstat | 1 files changed, 35 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemuriformes/path.py Sun Dec 10 17:19:30 2017 -0800 @@ -0,0 +1,35 @@ +""" +functions related to paths +""" + +import shutil +import tempfile + + +def ensure_dir(path): + """ensures `path` is a directory""" + + if os.path.exists(path): + assert os.path.isdir(path) + else: + os.makedirs(path) + return path + + +class TempDir(object): + """temporary directory context manager""" + # For inspiration see + # https://stackoverflow.com/questions/19296146/tempfile-temporarydirectory-context-manager-in-python-2-7 + + def __init__(self): + self.tmpdir = None + + def __enter__(self): + self.tmpdir = tempfile.mkdtemp() + return self.tmpdir + + def __exit__(self, *args): + if not self.tmpdir: + return + shutil.rmtree(self.tmpdir, ignore_errors=True) + self.tmpdir = None