Skip to content

File

list_files_with_extensions

List files in a directory with specified extensions or all files if no extensions are provided.

Parameters:

Name Type Description Default
directory Union[str, Path]

The directory path as a string or Path object.

required
extensions Optional[List[str]]

A list of file extensions to filter. Default is None, which lists all files.

None

Returns:

Type Description
List[Path]

A list of Path objects for the matching files.

Examples:

import supervision as sv

# List all files in the directory
files = sv.list_files_with_extensions(directory='my_directory')

# List only files with '.txt' and '.md' extensions
files = sv.list_files_with_extensions(
    directory='my_directory', extensions=['txt', 'md'])
Source code in supervision/utils/file.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def list_files_with_extensions(
    directory: Union[str, Path], extensions: Optional[List[str]] = None
) -> List[Path]:
    """
    List files in a directory with specified extensions or
        all files if no extensions are provided.

    Args:
        directory (Union[str, Path]): The directory path as a string or Path object.
        extensions (Optional[List[str]]): A list of file extensions to filter.
            Default is None, which lists all files.

    Returns:
        (List[Path]): A list of Path objects for the matching files.

    Examples:
        ```python
        import supervision as sv

        # List all files in the directory
        files = sv.list_files_with_extensions(directory='my_directory')

        # List only files with '.txt' and '.md' extensions
        files = sv.list_files_with_extensions(
            directory='my_directory', extensions=['txt', 'md'])
        ```
    """

    directory = Path(directory)
    files_with_extensions = []

    if extensions is not None:
        for ext in extensions:
            files_with_extensions.extend(directory.glob(f"*.{ext}"))
    else:
        files_with_extensions.extend(directory.glob("*"))

    return files_with_extensions

Comments