Skip to content
Snippets Groups Projects
utils.py 2.23 KiB
Newer Older
Kerstin Kaspar's avatar
Kerstin Kaspar committed
import os
from pathlib import Path
from datetime import datetime


def check_filepath(filepath: (str, Path),
                   makedir: bool = True,
                   overwrite: bool = False,
                   expand: str = 'date',
                   **kwargs) -> Path:
    """
    Checks a filepath existence and possibly creates directories
    :param filepath: filepath to the target
    :param makedir: create nonexistent directories in the filepath
    :param overwrite: toggles allowance to overwrite existing data in the filepath
    :param expand: 'date' (default): expands existing files with datetime (up to minute),
        'num': expands with running digit
    :return filepath: The correct path to the existing or created folder
    """
    filepath = Path(filepath)
    if not filepath.parent.exists():
        if makedir:
            os.makedirs(Path(filepath.parent))
        else:
            raise ValueError('Filepath does not exist. To create, rerun with makedir = True.')
    if not overwrite:
        if expand == 'date':
            if filepath.exists():
                filepath = Path(filepath.as_posix().replace(filepath.stem + filepath.suffix,
                                                            filepath.stem + '__{date}'.format(
                                                                date=datetime.now().strftime("%Y-%m-%d_%H-%M"))
                                                            + filepath.suffix))
        elif expand == 'num':
            i = (len(filepath.suffix) + 1) * -1
            while filepath.exists():
                if filepath.name[i].isdigit():
                    if int(filepath.name[i]) + 1 < 10:
                        filepath = Path(filepath.as_posix().replace(filepath.name[i],
                                                                    str(int(filepath.name[i]) + 1)))
                    else:
                        i -= 1
                else:
                    filepath = Path(filepath.as_posix().replace(filepath.stem + filepath.suffix,
                                                                filepath.stem + '__1' + filepath.suffix))

        else:
            raise ValueError('Can not expand with ' + expand + ', only date and num are valid.')
    return filepath