Skip to content

WorkingDirectory


Bases: contextlib.ContextDecorator

Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager.

Source code in ultralytics/yolo/utils/files.py
class WorkingDirectory(contextlib.ContextDecorator):
    """Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager."""

    def __init__(self, new_dir):
        """Sets the working directory to 'new_dir' upon instantiation."""
        self.dir = new_dir  # new dir
        self.cwd = Path.cwd().resolve()  # current dir

    def __enter__(self):
        """Changes the current directory to the specified directory."""
        os.chdir(self.dir)

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Restore the current working directory on context exit."""
        os.chdir(self.cwd)

__enter__()

Changes the current directory to the specified directory.

Source code in ultralytics/yolo/utils/files.py
def __enter__(self):
    """Changes the current directory to the specified directory."""
    os.chdir(self.dir)

__exit__(exc_type, exc_val, exc_tb)

Restore the current working directory on context exit.

Source code in ultralytics/yolo/utils/files.py
def __exit__(self, exc_type, exc_val, exc_tb):
    """Restore the current working directory on context exit."""
    os.chdir(self.cwd)

__init__(new_dir)

Sets the working directory to 'new_dir' upon instantiation.

Source code in ultralytics/yolo/utils/files.py
def __init__(self, new_dir):
    """Sets the working directory to 'new_dir' upon instantiation."""
    self.dir = new_dir  # new dir
    self.cwd = Path.cwd().resolve()  # current dir



increment_path


Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.

If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a directory if it does not already exist.

Parameters:

Name Type Description Default
path str, pathlib.Path

Path to increment.

required
exist_ok bool

If True, the path will not be incremented and returned as-is. Defaults to False.

False
sep str

Separator to use between the path and the incrementation number. Defaults to ''.

''
mkdir bool

Create a directory if it does not exist. Defaults to False.

False

Returns:

Type Description
pathlib.Path

Incremented path.

Source code in ultralytics/yolo/utils/files.py
def increment_path(path, exist_ok=False, sep='', mkdir=False):
    """
    Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.

    If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to
    the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the
    number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a
    directory if it does not already exist.

    Args:
        path (str, pathlib.Path): Path to increment.
        exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. Defaults to False.
        sep (str, optional): Separator to use between the path and the incrementation number. Defaults to ''.
        mkdir (bool, optional): Create a directory if it does not exist. Defaults to False.

    Returns:
        (pathlib.Path): Incremented path.
    """
    path = Path(path)  # os-agnostic
    if path.exists() and not exist_ok:
        path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')

        # Method 1
        for n in range(2, 9999):
            p = f'{path}{sep}{n}{suffix}'  # increment path
            if not os.path.exists(p):  #
                break
        path = Path(p)

    if mkdir:
        path.mkdir(parents=True, exist_ok=True)  # make directory

    return path



file_age


Return days since last file update.

Source code in ultralytics/yolo/utils/files.py
def file_age(path=__file__):
    """Return days since last file update."""
    dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime))  # delta
    return dt.days  # + dt.seconds / 86400  # fractional days



file_date


Return human-readable file modification date, i.e. '2021-3-26'.

Source code in ultralytics/yolo/utils/files.py
def file_date(path=__file__):
    """Return human-readable file modification date, i.e. '2021-3-26'."""
    t = datetime.fromtimestamp(Path(path).stat().st_mtime)
    return f'{t.year}-{t.month}-{t.day}'



file_size


Return file/dir size (MB).

Source code in ultralytics/yolo/utils/files.py
def file_size(path):
    """Return file/dir size (MB)."""
    if isinstance(path, (str, Path)):
        mb = 1 << 20  # bytes to MiB (1024 ** 2)
        path = Path(path)
        if path.is_file():
            return path.stat().st_size / mb
        elif path.is_dir():
            return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
    return 0.0



get_latest_run


Return path to most recent 'last.pt' in /runs (i.e. to --resume from).

Source code in ultralytics/yolo/utils/files.py
def get_latest_run(search_dir='.'):
    """Return path to most recent 'last.pt' in /runs (i.e. to --resume from)."""
    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
    return max(last_list, key=os.path.getctime) if last_list else ''



make_dirs


Source code in ultralytics/yolo/utils/files.py
def make_dirs(dir='new_dir/'):
    # Create folders
    dir = Path(dir)
    if dir.exists():
        shutil.rmtree(dir)  # delete dir
    for p in dir, dir / 'labels', dir / 'images':
        p.mkdir(parents=True, exist_ok=True)  # make dir
    return dir




Created 2023-04-16, Updated 2023-05-17
Authors: Glenn Jocher (4)