view 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
line wrap: on
line source

"""
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