fileutils - Infernet ML
Description: Infernet ML Documentation

Skip to content

# Module: `fileutils`

## `prune_old_items(directory, threshold=DEFAULT_THRESHOLD)`

Prune old items in a directory to keep the number of items below a threshold.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`directory` | `Path` | Directory to prune. | required
`threshold` | `int` | Maximum number of items to keep in the directory. | `DEFAULT_THRESHOLD`

Returns:

Type | Description
--- | ---
`None` | None

Source code in `src/infernet_ml/utils/fileutils.py`

     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    def prune_old_items(directory: Path, threshold: int = DEFAULT_THRESHOLD) -> None:
        """
        Prune old items in a directory to keep the number of items below a threshold.

        Args:
            directory (Path): Directory to prune.
            threshold (int): Maximum number of items to keep in the directory.

        Returns:
            None
        """
        items = list(directory.iterdir())

        if len(items) > threshold:
            items.sort(key=lambda x: x.stat().st_mtime)
            items_to_remove = len(items) - threshold
            for item in items[:items_to_remove]:
                try:
                    if item.is_file():
                        item.unlink()  # Remove file
                    elif item.is_dir():
                        shutil.rmtree(item)  # Remove directory and its contents
                except Exception as e:
                    print(f"Error deleting {item}: {e}")