Scan a directory recursively, in breadth-first order. The returned entries are sorted according to the given key. The default is to sort by name. If the directory does not exist, return an empty list.
(
path: str | os.PathLike[str],
sort_key: Callable[[os.DirEntry[str]], object] = lambda entry: entry.name,
)
| 939 | |
| 940 | |
| 941 | def scandir( |
| 942 | path: str | os.PathLike[str], |
| 943 | sort_key: Callable[[os.DirEntry[str]], object] = lambda entry: entry.name, |
| 944 | ) -> list[os.DirEntry[str]]: |
| 945 | """Scan a directory recursively, in breadth-first order. |
| 946 | |
| 947 | The returned entries are sorted according to the given key. |
| 948 | The default is to sort by name. |
| 949 | If the directory does not exist, return an empty list. |
| 950 | """ |
| 951 | entries = [] |
| 952 | # Attempt to create a scandir iterator for the given path. |
| 953 | try: |
| 954 | scandir_iter = os.scandir(path) |
| 955 | except FileNotFoundError: |
| 956 | # If the directory does not exist, return an empty list. |
| 957 | return [] |
| 958 | # Use the scandir iterator in a context manager to ensure it is properly closed. |
| 959 | with scandir_iter as s: |
| 960 | for entry in s: |
| 961 | try: |
| 962 | entry.is_file() |
| 963 | except OSError as err: |
| 964 | if _ignore_error(err): |
| 965 | continue |
| 966 | # Reraise non-ignorable errors to avoid hiding issues. |
| 967 | raise |
| 968 | entries.append(entry) |
| 969 | entries.sort(key=sort_key) # type: ignore[arg-type] |
| 970 | return entries |
| 971 | |
| 972 | |
| 973 | def visit( |